pathlib 파일경로 라이브러리

김신영·2025년 10월 11일

Python

목록 보기
10/10
post-thumbnail

pathlib.Path의 실용적인 사용법을 알려드리겠습니다.

1. 기본 - 경로 생성

from pathlib import Path

# 현재 디렉토리
current = Path('.')
current = Path.cwd()  # 절대 경로로

# 홈 디렉토리
home = Path.home()  # /home/username 또는 C:\Users\username

# 상대 경로
data_path = Path('data/train/images')

# 절대 경로
abs_path = Path('/home/user/project/data')

# 경로 조합 (운영체제 독립적)
base = Path('project')
full_path = base / 'data' / 'train' / 'model.pkl'
# project/data/train/model.pkl

2. 경로 정보 확인

file_path = Path('data/train/model.pkl')

# 파일명
file_path.name          # 'model.pkl'
file_path.stem          # 'model' (확장자 제외)
file_path.suffix        # '.pkl'

# 디렉토리
file_path.parent        # data/train
file_path.parents[0]    # data/train
file_path.parents[1]    # data

# 존재 여부
file_path.exists()      # True/False
file_path.is_file()     # 파일인가?
file_path.is_dir()      # 디렉토리인가?

# 절대 경로 변환
file_path.resolve()     # /full/absolute/path/data/train/model.pkl

3. 디렉토리 생성

# 디렉토리 생성
output_dir = Path('output/models/v1')

# 부모 디렉토리도 함께 생성, 이미 있어도 에러 안남
output_dir.mkdir(parents=True, exist_ok=True)

# 단일 디렉토리만 생성 (부모가 없으면 에러)
Path('temp').mkdir()

4. 파일 읽기/쓰기

config_path = Path('config.txt')

# 텍스트 파일 읽기
content = config_path.read_text(encoding='utf-8')

# 텍스트 파일 쓰기
config_path.write_text('setting=value', encoding='utf-8')

# 바이너리 파일
data = config_path.read_bytes()
config_path.write_bytes(b'binary data')

5. 파일/디렉토리 탐색

data_dir = Path('data')

# 현재 디렉토리의 모든 항목
for item in data_dir.iterdir():
    print(item)

# 특정 패턴 찾기
for txt_file in data_dir.glob('*.txt'):
    print(txt_file)

# 재귀적으로 찾기 (하위 폴더 포함)
for py_file in data_dir.rglob('*.py'):
    print(py_file)

# 예시: CSV 파일만 찾기
csv_files = list(data_dir.glob('*.csv'))

6. 실무 예제

데이터 로딩

from pathlib import Path
import pandas as pd

# 프로젝트 구조
# project/
#   ├── data/
#   │   ├── train.csv
#   │   └── test.csv
#   └── main.py

# 경로 설정
BASE_DIR = Path(__file__).parent  # main.py가 있는 디렉토리
DATA_DIR = BASE_DIR / 'data'

# 파일 읽기
train_path = DATA_DIR / 'train.csv'
if train_path.exists():
    df = pd.read_csv(train_path)
else:
    print(f"파일이 없습니다: {train_path}")

모델 저장/로드

from pathlib import Path
import joblib

# 모델 저장 디렉토리 생성
model_dir = Path('models/experiment_001')
model_dir.mkdir(parents=True, exist_ok=True)

# 모델 저장
model_path = model_dir / 'best_model.pkl'
joblib.dump(model, model_path)

# 모델 로드
if model_path.exists():
    model = joblib.load(model_path)

로그 파일 관리

from pathlib import Path
from datetime import datetime

# 로그 디렉토리
log_dir = Path('logs')
log_dir.mkdir(exist_ok=True)

# 날짜별 로그 파일
today = datetime.now().strftime('%Y%m%d')
log_file = log_dir / f'app_{today}.log'

# 로그 추가
with open(log_file, 'a') as f:
    f.write(f'{datetime.now()}: Log message\n')

파일 정리

from pathlib import Path

data_dir = Path('data/temp')

# .tmp 파일 모두 삭제
for tmp_file in data_dir.glob('*.tmp'):
    tmp_file.unlink()  # 파일 삭제

# 빈 디렉토리 삭제
if data_dir.exists() and not any(data_dir.iterdir()):
    data_dir.rmdir()

7. 경로 비교 및 변환

path = Path('data/train/model.pkl')

# 확장자 변경
new_path = path.with_suffix('.joblib')
# data/train/model.joblib

# 파일명 변경
new_path = path.with_name('best_model.pkl')
# data/train/best_model.pkl

# stem 변경
new_path = path.with_stem('final_model')
# data/train/final_model.pkl

# 문자열로 변환
str(path)           # 'data/train/model.pkl'
path.as_posix()     # 'data/train/model.pkl' (항상 /)

8. 유용한 패턴

프로젝트 루트 찾기

from pathlib import Path

def find_project_root(marker='.git'):
    """프로젝트 루트 디렉토리 찾기"""
    current = Path.cwd()
    for parent in [current] + list(current.parents):
        if (parent / marker).exists():
            return parent
    return current

project_root = find_project_root()
config_path = project_root / 'config.yaml'

안전한 파일 쓰기

from pathlib import Path

def safe_write(path, content):
    """디렉토리가 없으면 생성하고 파일 쓰기"""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content)

safe_write('output/results/summary.txt', 'Results here')

파일 크기 확인

from pathlib import Path

file_path = Path('data/large_file.csv')

if file_path.exists():
    size_bytes = file_path.stat().st_size
    size_mb = size_bytes / (1024 * 1024)
    print(f"파일 크기: {size_mb:.2f} MB")

9. os.path와 비교

# os.path 방식
import os
path = os.path.join('data', 'train', 'model.pkl')
exists = os.path.exists(path)
dirname = os.path.dirname(path)

# pathlib 방식 (더 간결)
from pathlib import Path
path = Path('data') / 'train' / 'model.pkl'
exists = path.exists()
dirname = path.parent

핵심 요약

from pathlib import Path

# 생성
path = Path('data') / 'file.txt'

# 확인
path.exists(), path.is_file(), path.is_dir()

# 정보
path.name, path.stem, path.suffix, path.parent

# 생성
path.parent.mkdir(parents=True, exist_ok=True)

# 읽기/쓰기
path.read_text(), path.write_text('content')

# 탐색
path.glob('*.txt'), path.rglob('**/*.py')
profile
Hello velog!

0개의 댓글