Python입출력과 예외

with문과 Context Manager

`with open(...) as f`처럼 context manager를 쓰는 기본 구조와 `contextlib` 유틸을 함께 정리합니다.

마지막 수정 2026년 3월 17일

기본 패턴

python
from pathlib import Path

with Path("data.txt").open("r", encoding="utf-8") as handle:
    content = handle.read()

설명

  • with 블록은 enter/exit 메서드가 있는 context manager를 자동으로 닫습니다.
  • pathlib.Path.open, open, contextlib.suppress, contextlib.ExitStack처럼 다양한 매니저가 있습니다.
  • contextlib.contextmanager 데코레이터로 직접 간단한 manager를 만들 수도 있습니다.

짧은 예제

python
from contextlib import suppress

with suppress(FileNotFoundError):
    Path("temp.txt").unlink()

빠른 정리

항목역할
with expr as targetenter/exit 자동 호출
contextlib.suppress특정 예외 무시
ExitStack여러 manager 동적 등록

주의할 점

with 블록을 벗어나면 파일이 항상 닫히니, 파일을 장시간 열어 비동기로 처리할 때도 반드시 with를 쓰세요.