파일 입출력

✒️ 2025-05-19 10:22 내용 수정

Do it! 점프 투 파이썬(2017년 발행) 내용을 정리


파일 생성

f = open("새파일.txt", 'w')
f.close()
파일 열기 모드 설명
r 읽기 전용 모드
w 쓰기 모드
해당 파일이 이미 존재하면 원래 내용이 모두 제거되고, 해당 파일이 존재하지 않으면 새 파일을 생성
a 추가 모드(파일 마지막에 새 내용 추가)

python_file_input 1.png

f = open("C:/Users/user/Desktop/파이썬테스트.txt", 'w')
f.close()
with open("새파일.txt", "w") as f:
	f.write("with 테스트")

파일에 내용을 새로 작성하기

f = open("C:/Users/user/Desktop/새파일.txt", 'w')
for i in range(1, 11):
	data = f"{i}번째 줄 입니다.\n"
	f.write(data)
f.close()

python_file_input 2.png


파일 읽기

  1. readline() 함수를 사용하여 파일의 첫 번째 줄을 읽어 출력할 수 있다.
    • 파일을 읽을 때 open(파일명, 'r')로 설정해야 파일의 기존 내용이 삭제되지 않는다.
f = open("C:/Users/user/Desktop/새파일.txt", 'r')
line = f.readline()
print(line)
f.close()

python_file_input 3.png

  1. readlines() 함수로 파일의 모든 줄을 읽어 출력할 수 있다.
    • readlines() 함수는 파일의 모든 줄을 읽어 각각의 줄을 요소로 가지는 리스트를 반환한다.
f = open("C:/Users/user/Desktop/Python 실습/새파일.txt", 'r')
lines = f.readlines()
for line in lines:
	print(line)
f.close()

python_file_input 4.png

f = open("C:/Users/user/Desktop/Python 실습/새파일.txt", 'r')
lines = f.readlines()
for line in lines:
	print(line)
f.close()

python_file_input 5.png

  1. read() 함수를 사용하면 파일의 내용 전체를 문자열로 가져올 수 있다.
f = open("C:/Users/user/Desktop/Python 실습/새파일.txt", 'r')
data = f.read()
print(data)
f.close()

python_file_input 6.png

  1. open()이 파일 객체를 리턴하는 것을 이용해 for문과 함께 파일의 모든 내용을 줄 단위로 가져올 수 있다.
f = open("C:/Users/user/Desktop/Python 실습/새파일.txt", 'r')
for line in f:
	print(line)
f.close()

python_file_input 7.png


파일의 마지막 줄에 새 내용 추가

f = open("C:/Users/user/Desktop/Python 실습/새파일.txt", 'a')
alpha = ['a', 'b', 'c', 'd', 'e']
for i in alpha:
	f.write(i)
f.close()

python_file_input 8.png