with와 파일 읽기
파일을 열고 사용한 뒤 자동으로 닫히게 합니다.
기본 문법
with open(path, mode, encoding="utf-8") as file:작은 예제 python
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "note.txt"
path.write_text("안녕하세요", encoding="utf-8")
with open(path, encoding="utf-8") as file:
print(file.read())실행 결과
안녕하세요
헷갈리기 쉬운 점
- 문자 인코딩을 직접 지정하면 컴퓨터의 기본 인코딩에 의존하지 않습니다.
- w 모드는 기존 내용을 덮어씁니다. 예제는 전용 임시 폴더에서 파일을 만들어 실제 문서를 건드리지 않습니다.