파이썬에서 파일을 다루는 방법에 관해서 알아보자.
with
자원을 획득하고, 사용한 뒤, 반납할 때 주로 사용한다.
with open('myFile.txt', 'r') as my_file:
contents = my_file.read()
print(contents)
with 블록을 나가면서 자동으로 자원을 반납하기 때문에 파일 처리 시 close() 함수를 사용하지 않아도 된다.
readlines 함수
파일을 한 줄씩 읽어 list 타입으로 반환한다.
with open('myFile.txt', 'r') as my_file:
content_list = my_file.readlines()
print(type(content_list))
# 출력: list
readline 함수
실행할 때마다 한 줄씩 반환한다.
with open('myFile.txt', 'r') as my_file:
while True:
line = my_file.readline()
if not line:
break
print(line)
'Backend > Python' 카테고리의 다른 글
pyenv와 pyenv-virtualenv로 파이썬 버전 관리하기 (0) | 2023.12.27 |
---|---|
코드 스타일 통일을 위해 Black 적용하기 (0) | 2023.04.26 |
[Python] Exception Handling (0) | 2023.03.08 |
[Python] 모듈과 패키지 (0) | 2023.03.08 |
[Python] decorator (0) | 2023.03.07 |