open()함수는 주로 텍스트 파일(.txt)을 읽거나 쓸 때 사용된다.
파일을 읽고, 쓰고, 수정할 때, open()함수를 사용한다.
open()을 하면 파일이 열린 채 메모리에 계속 남아있기 때문에, 사용 후에는 close()를 해주어야 한다.
f = open('filename.txt', 'mode')
f.close()
with는 open과 close 과정을 자동으로 관리해준다.
close()를 따로 하지 않아도 메모리에서 자동으로 제거됨with open('filename.txt', 'r', encoding="uft-8") as f:
data = f.readlines()
read(): 파일 전체 내용을 하나의 문자열로 읽음readline(): 한 줄씩 읽음
\\n이 포함됨readlines(): 파일의 모든 줄을 리스트로 읽음
write(): 파일에 문자열을 씀writelines(): 리스트의 각 문자열을 순차적으로 그대로 씀
\\n이 있어야 줄 바꿈이 됨각 모드는 혼합해서 쓸 수 있으며, Default는 'rt’ 모드이다.
r: 읽기 모드로 파일 열기 (Default)
f = open('filename.txt', 'r')
data = f.readlines()
f.close()
w: 쓰기 모드로 파일 열기
f = open('filename.txt', 'w')
f.write("Hello World!")
f.close()
x: 쓰기 모드로 파일 열기
f = open('filename.txt', 'x')
f.write("Hello World!")
f.close()
a: 추가 모드(append mode)로 파일 열기
f = open('filename.txt', 'a')
f.write("Hello World!")
f.close()
b: 바이너리 파일 모드로 열기
f = open('filename.txt', 'rb')
data = f.readlines()
f.close()
t: 텍스트 파일 모드로 열기 (Default)
f = open('filename.txt', 'rb')
data = f.readlines()
f.close()
Buffering policy(버퍼링 정책)을 결정하는 인자이며, 정수 값을 가진다.