test.txt 파일을 먼저 만들었다.
open(파일경로, 파일모드)
read()
file = open('./test.txt', 'r')
str = file.read()
print(f'파일 내용 : {str}')
file.close()
write()
file = open('./write.txt', 'w')
strCnt = file.write('Hello World~')
file.close()
write.txt는 없는 파일이지만, "w"모드에서는 파일이 없으면 파일을 만든 다음 쓴다.
file = open('./write.txt', 'w')
strCnt = file.write('0123')
file.close()
Hello World~를 지우고 0123이을 썼다.
file = open('./write.txt', 'a')
strCnt = file.write('Hello World~')
file.close()
write.txt를 삭제하고 코드를 실행했다.
txt파일이 정상적으로 만들어졌다.
file = open('./write.txt', 'a')
strCnt = file.write('0123')
file.close()
Hello World~ 뒤에 0123을 붙여 썼다.
만약 줄바꿈이나 띄어쓰기를 넣고싶으면 \n, \t 등을 사용하면 된다.
close()
: 파일 닫기file을 open()한 경우, file.close() 를 사용해 파일을 반드시 닫아야 한다.
with open('test.txt', 'a') as f:
f.write('python')
with open('test.txt', 'a') as f
는 f = open('./test.txt', 'a')
와 동일한 의미다.
as뒤에 오는 이름이 open()으로 연 파일 객체가 된다.
f말고도 file로 적는것도 당연히 가능하다.
with open('test.txt', 'r') as file:
print(file.read())
위에서 적은 내용을 with~as구문을 사용해 읽어왔다.
test.txt 파일을 이렇게 여러줄로 작성해봤다.
위와 동일한 방법을 사용해 읽어올수 있지만 이 경우에는 내용 전체가 eng 변수 하나에 저장이 된다.
만약 한줄씩 저장하고 싶다면 for문을 사용하면 된다.
for문을 사용해면 f안에 있는 내용을 줄바꿈을 기준으로 분리할수 있다!