본문 바로가기

프로그래밍/Python

[파이썬, Python] 텍스트 파일 불러오기 (open, close, with)

728x90

텍스트 파일 불러오는 법

 

open(filename.txt, mode)

 

mode description
"r" Read, 읽기 모드
"w" Write, 쓰기 모드 (파일 존재할 시 새로 쓰기)
"a" Append, 추가 모드, 기존 파일에 내용 추가할 때 사용
"x" Create, 파일 생성 (파일 존재할 시 에러)

 

1. 파일 새로 생성하여 쓰기

f = open("file.txt","w")
f.write("hello, world!\n")
f.close()

 

결과

 

2. 파일에 내용 추가하기

f = open("file.txt","a")
f.write("I'm hungry.")
f.close()

 

결과

 

3. with문 사용하여 파일 불러오기

 - with문 안에서만 open이 실행되있으므로, 따로 close를 해줄 필요가 없습니다.

with open("file.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        print(line)

 

결과