shutil(shell utilities)은 「파일·디렉토리의 복사·이동·삭제·압축 같은 고수준 작업」을 다루는 표준 라이브러리입니다.
os 모듈은 「개별 파일 단위」, shutil은 「디렉토리 전체나 큰 단위」 작업에 강합니다.
복사·이동.
shutil.copy("src", "dst") — 파일 복사.
shutil.copy2("src", "dst") — 메타데이터(타임스탬프 등) 포함 복사.
shutil.copytree("src_dir", "dst_dir") — 디렉토리 통째로 복사.
shutil.move("src", "dst") — 이동(또는 이름 변경).
삭제.
shutil.rmtree("dir") — 디렉토리와 그 안의 모든 것 삭제.
매우 강력하니 신중하게 — 「rm -rf」와 같은 효과로 되돌릴 수 없습니다.
사용 전 경로를 한 번 더 확인하는 습관이 안전합니다.
압축.
shutil.make_archive("backup", "zip", "data_dir") — data_dir를 backup.zip으로 압축.
shutil.unpack_archive("backup.zip", "out_dir") — 압축 해제.
zip·tar·gztar·bztar·xztar 형식을 지원합니다.
기타 유용한 함수.
shutil.disk_usage("/") — 디스크 사용량 (total, used, free).
shutil.which("python") — 실행파일 경로(어느 디렉토리의 python이 실행되는지).
shutil.get_terminal_size() — 터미널 크기.
「자동 백업 스크립트」, 「임시 작업 디렉토리 정리」 같은 자동화에서 거의 표준 라이브러리입니다.
한 줄 요약
shutil은 파일·디렉토리의 고수준 작업(복사·이동·삭제·압축)을 다룹니다.
copytree·rmtree·make_archive가 자주 쓰이며, rmtree는 신중하게 써야 합니다.
더 알아볼 것
- os.remove vs shutil.rmtree 비교
- make_archive의 형식 옵션
- Path.unlink vs shutil.rmtree