파일 읽고 쓰기

suyeon lee·2021년 4월 22일

python

목록 보기
11/11

f = open('새파일.txt', encoding='utf-8') #텍스트 파일을 불러온다
print(f.read()) # 파일을 읽으면 커서가 마지막 줄에가있는상태
print(f.read()) #커서가 마지막줄인 상태에서 같은 파일을 똑읽는거기때문에 출력은 1번만됨

파일을 객체에 담아 출려하면 여러번 출력가능

content = f.read()
f.close() #파일 닫기
print(content)
print(content)

파일을 자동으로 닫아주는 with open as

with open('새파일.txt', encoding='utf-8')as f:
content = f.read()
print(content)

파일 쓰기(파일이 없는경우 새로 만들어줌)

#계속 쓰기를 하면 덮어쓰기가 되서 작성글추가는 안됨
with open('채소.txt', 'w', encoding='utf-8')as f:
f.write('무\n')
f.write('배추\n')
f.write('토마토\n')
f.write('브로콜리\n')

a일때는 작성글을 추가해준다

with open('채소.txt', 'a', encoding='utf-8')as f:
f.write('무\n')
f.write('배추\n')
f.write('토마토\n')
f.write('브로콜리\n')

with open('새파일.txt', encoding='utf-8') as f1:
c1 = f1.read()

with open('채소.txt', encoding='utf-8')as f2:
c2 = f2.read()

a+는 읽고 쓰기 둘다가능

with open('과일채소.txt', 'a+', encoding='utf-8')as f:
f.write(c1)
f.write(c2)
f.seek(0) # 커서를 처음으로 이동시킴

# why?글을 작성하고나면 커서가 마지막줄에 위치하기때문에 쓰고난후 읽을려면 커서를 처음으로 이동시켜줘야함
print(f.read())

0개의 댓글