PYTHON · 파일/IO
pathlib 심화
pathlib의 고급 기능으로 경로 조작, 파일 검색, 메타데이터 접근을 수행합니다.
파일/IO중급pathlibPath경로파일
핵심 설명
pathlib의 고급 기능으로 경로 조작, 파일 검색, 메타데이터 접근을 수행합니다.
Python code
from pathlib import Path
# 경로 조합 (/ 연산자)
base = Path("/home/user")
config = base / "projects" / "app" / "config.yaml"
print(config) # /home/user/projects/app/config.yaml
print(config.parent) # /home/user/projects/app
print(config.stem) # config
print(config.suffix) # .yaml
print(config.name) # config.yaml
# 경로 변환
print(config.with_suffix(".json")) # .../config.json
print(config.with_name("settings.yaml"))
# 현재 디렉터리 기준
here = Path.cwd()
print(f"현재: {here}")
# 파일 검색 (glob)
# python_files = list(Path(".").rglob("*.py")) # 재귀 검색
# for f in python_files[:5]:
# print(f" {f}: {f.stat().st_size} bytes")
# 파일 읽기/쓰기 (한 줄)
# Path("output.txt").write_text("Hello!", encoding="utf-8")
# content = Path("output.txt").read_text(encoding="utf-8")
# 경로 존재 확인
p = Path("/tmp/test")
print(f"존재: {p.exists()}")
print(f"파일: {p.is_file()}")
print(f"디렉터리: {p.is_dir()}")
# 부모 순회
for parent in config.parents:
print(f" 상위: {parent}")학습 팁
pathlib.Path의 / 연산자는 os.path.join()보다 직관적이고 크로스 플랫폼 호환됩니다.
주의할 점
open()에 Path 객체를 전달할 수 있지만, 일부 오래된 라이브러리는 문자열만 받습니다. str(path)로 변환하세요.
자주 묻는 질문
pathlib 심화란 무엇인가요?
pathlib 의 고급 기능으로 경로 조작, 파일 검색, 메타데이터 접근을 수행합니다.
pathlib 심화 학습 시 주의할 점은 무엇인가요?
open() 에 Path 객체를 전달할 수 있지만, 일부 오래된 라이브러리는 문자열만 받습니다. str(path) 로 변환하세요.