본문 바로가기
C.W.K.
Stream
Lesson 02 of 06 · published

pathlib — 경로를 문자열이 아닌 객체로 다루기

~20 min · pathlib, path, os.path

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

Path에 경로 연산을 모아

Path는 운영체제에 맞는 경로 객체를 만들고 / 연산자로 조각을 이어. home과 cwd에서 시작하고 name·stem·suffix·parent·parts로 구성 요소를 읽을 수 있어.

존재와 종류를 직접 물어

exists, is_file, is_dir, stat가 문자열 조작 없이 파일 상태를 알려줘. 작은 파일 전체는 read_text/write_text나 bytes 짝으로 열고 닫는 일을 한 호출에 맡길 수 있어.

glob은 Path를 돌려줘

glob은 현재 아래, rglob은 재귀적으로 패턴에 맞는 경로를 찾아. 새 코드는 pathlib 한 방식으로 유지하고 문자열만 받는 옛 API 경계에서만 str로 바꿔.

Code

Path를 만들고 /로 이어 붙이기·python
from pathlib import Path

# 생성
p = Path("/Users/you_username")
print(p)                       # /Users/you_username

# 합치기 — / 연산자
file_path = p / "Documents" / "notes.txt"
print(file_path)               # /Users/you_username/Documents/notes.txt

# 유용한 시작점
print(Path.home())             # /Users/you_username
print(Path.cwd())              # 현재 작업 디렉토리
print(Path(".").resolve())     # 현재 dir, 절대 경로
경로의 존재와 종류 확인하기·python
from pathlib import Path

p = Path("/etc/hostname")
print(p.exists())             # True
print(p.is_file())            # True
print(p.is_dir())             # False

# 분해
q = Path("/etc/profile.d/00-aliases.sh")
print(q.name)                 # '00-aliases.sh'
print(q.stem)                 # '00-aliases'        — suffix 없는 이름
print(q.suffix)               # '.sh'
print(q.parent)                # PosixPath('/etc/profile.d')
print(q.parts)                # ('/', 'etc', 'profile.d', '00-aliases.sh')

# Stat
import time
stat = p.stat()
print("크기:", stat.st_size)
print("수정:", time.ctime(stat.st_mtime))
작은 텍스트 파일 한 번에 읽고 쓰기·python
from pathlib import Path

p = Path("/tmp/note.txt")

# 쓰기
p.write_text("hello pippa\n", encoding="utf-8")

# 읽기
content = p.read_text(encoding="utf-8")
print(content)

# 바이트
b = Path("/tmp/raw.bin")
b.write_bytes(b"\xDE\xAD\xBE\xEF")
print(b.read_bytes())          # b'\xde\xad\xbe\xef'
glob과 rglob으로 파일 찾기·python
from pathlib import Path

# 디렉토리의 모든 .py (비재귀)
for py in Path(".").glob("*.py"):
    print(py)

# 재귀 — cwd 아래 모든 .py
for py in Path(".").rglob("*.py"):
    print(py)

# 패턴 변형
# *  어떤 글자 (no /)
# ** 어떤 디렉토리 (rglob 와)
# ?  한 글자
# [abc]  a, b, c 중 하나

# count / sort 원하면 list()
files = sorted(Path(".").glob("*.txt"))
print(f"{len(files)} 파일")
디렉터리 생성·이름 변경·삭제·python
from pathlib import Path

# 디렉토리 생성 (parents=True 가 중간 만듦, exist_ok 가 에러 억제)
d = Path("/tmp/nested/dir")
d.mkdir(parents=True, exist_ok=True)
print(d.exists())             # True

# 안에 파일
(d / "child.txt").write_text("hi", encoding="utf-8")

# rename
original = d / "child.txt"
renamed = original.rename(d / "renamed.txt")
print(renamed)                # /tmp/nested/dir/renamed.txt

# 파일 삭제
renamed.unlink(missing_ok=True)
print(renamed.exists())       # False

# 빈 디렉토리 제거
d.rmdir()                     # 안 비면 raise
# 비어있지 않은 트리엔 — shutil.rmtree(d)

External links

Exercise

pathlib로 /tmp/quest_dir를 만들고 내용이 다른 a.txt, b.txt, c.txt를 써. glob으로 이름과 크기를 출력하고 /tmp에서 rglob으로 다시 찾은 뒤 세 파일과 디렉터리를 정리해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.