Data Science/python
open() 함수로 텍스트 파일 읽기/쓰기/추가하기/만들기
jay3108
2021. 12. 24. 16:47
1. 파일 읽기
파이썬에서는 텍스트 파일을 다루기 위해 open() 함수 사용
f= open("파일명","파일 열기 모드")
f.close
- 파일 열기 모드 -> r : 읽기모드 / w : 쓰기모드 / a : 추가 모드 - 파일의 마지막에 새로운 내용 추가
# 읽기 모드로 "dream.txt" 텍스트 파일 열기
f = open("dream.txt", "r") # 파일 객체 f에 파일 정보 저장
contents = f.read() # read() 함수로 해당 파일의 텍스트를 읽어서 변수에 저장
print(contents) # 저장된 변수 출력
f.close() # close() 함수로 파일 종료
I have a dream a song to sing
to help me cope with anything
if you see the wonder of a fairy tale
you can take the future even
if you fail I believe in angels
something good in everything
with문 + open 함수로 파일 열기 : close() 사용하지 않아도 들여쓰기가 끝나면 파일 사용 종료
- 해당 파일 객체는 = 로 할당하지 않고, as문을 사용하여 변수명에 할당함
with open("dream.txt","r") as my_file:
contents = my_file.read()
print(contents)
I have a dream a song to sing
to help me cope with anything
if you see the wonder of a fairy tale
you can take the future even
if you fail I believe in angels
something good in everything
2. 파일 쓰기
특정 자료를 텍스트 파일로 저장하기 : open() 으로 빈 텍스트 파일을 쓰기 모드로 만들고 wirte()로 저장해주는 개념
# 텍스트 파일로 저장
f = open('noun_set.txt','w')
f.write(str(noun_set))
f.close()
인코딩(encoding) : 텍스트 파일 저장 시 사용하는 표준을 지정하는 것 / 어떤 텍스트를 체계에 맞게 저장하는 것
- utf8, cp949(윈도). euc-kr
f = open("count_log.txt", 'w', encoding = "utf8")
for i in range(1, 6):
data = "%d번째 줄이다.\n" % i
print(data)
f.write(data)
f.close()
1번째 줄이다.
2번째 줄이다.
3번째 줄이다.
4번째 줄이다.
5번째 줄이다.
3. 파일 추가 모드
기존의 있던 파일을 w로 부르면 기존 파일이 삭제되고 새로운 내용만 기록된다.
따라서 기존 내용에 내용을 추가하려면 추가 모드 a를 사용한다.
with open("count_log.txt", 'a', encoding = "utf8") as f:
for i in range(1, 11):
data = "%d번째 줄이다.\n" % i
print(data)
f.write(data)