본문 바로가기

IT 기본/파이썬

python에서 with문

사용목적

파일 입출력 후 close를 항상 해주어야 하지만, with 사용시에 close를 하지 않아도 되는 이점이 있다. 

파일 입출력

f = open('test.txt', 'r')
print(f.readline())
f.close()

with을 사용해 파일 입출력

f = open('test.txt', 'r')
with f as in_file:
    print(in_file.readlines()) 

또는

with open('test.txt', 'r') as in_file:
    print(in_file.readlines()) 

'IT 기본 > 파이썬' 카테고리의 다른 글

python에서 axis(축)  (1) 2020.06.28