Python의 shutil 모듈은 고수준의 파일 연산을 제공하며, 파일 및 디렉토리 작업을 쉽게 수행할 수 있도록 도와줍니다. 이 매뉴얼에서는 shutil 모듈의 다양한 함수와 그 사용 방법에 대해 자세히 설명합니다.
1. 개요
Python의 shutil 모듈은 파일 복사, 이동, 삭제와 같은 고수준의 파일 연산을 수행하는 데 사용됩니다. 이 모듈은 파일 시스템에서 일반적으로 수행되는 작업을 단순화하여 사용자에게 편리함을 제공합니다.
2. 주요 함수
shutil.copy(src, dst)
파일을 복사합니다. src는 원본 파일 경로, dst는 대상 파일 경로입니다.
import shutil
shutil.copy('source.txt', 'destination.txt')
shutil.copy2(src, dst)
shutil.copy와 유사하지만, 메타데이터(예: 수정 시간)를 포함하여 파일을 복사합니다.
import shutil
shutil.copy2('source.txt', 'destination.txt')
shutil.copytree(src, dst)
디렉토리와 그 내용을 재귀적으로 복사합니다.
import shutil
shutil.copytree('source_directory', 'destination_directory')
shutil.move(src, dst)
파일이나 디렉토리를 이동합니다. 원본 파일은 대상 위치로 이동되며, 원본 위치에서는 삭제됩니다.
import shutil
shutil.move('source.txt', 'new_directory/source.txt')
shutil.rmtree(path)
디렉토리와 그 내용을 모두 삭제합니다.
import shutil
shutil.rmtree('directory_to_delete')
shutil.disk_usage(path)
주어진 경로의 디스크 사용량을 반환합니다. 반환 값은 총 용량, 사용된 용량, 사용 가능한 용량의 튜플입니다.
import shutil
total, used, free = shutil.disk_usage('/')
print(f"Total: {total}, Used: {used}, Free: {free}")
3. 고급 사용법
사용자 정의 오류 처리
shutil 모듈의 함수들은 파일 시스템 작업 중 발생할 수 있는 예외를 처리할 수 있도록 도와줍니다.
import shutil
import os
def handle_error(func, path, exc_info):
print(f"Error handling file {path}")
shutil.rmtree('directory_to_delete', onerror=handle_error)
압축 및 압축 해제
shutil 모듈은 디렉토리를 압축하거나 압축을 해제할 수 있는 기능도 제공합니다.
import shutil
# 디렉토리 압축
shutil.make_archive('archive_name', 'zip', 'directory_to_compress')
# 압축 해제
shutil.unpack_archive('archive_name.zip', 'extract_to_directory')
4. 주요 메서드 요약
shutil.copy(src, dst): 파일 복사shutil.copy2(src, dst): 메타데이터를 포함하여 파일 복사shutil.copytree(src, dst): 디렉토리와 그 내용 재귀적 복사shutil.move(src, dst): 파일이나 디렉토리 이동shutil.rmtree(path): 디렉토리와 그 내용 모두 삭제shutil.disk_usage(path): 디스크 사용량 반환shutil.make_archive(base_name, format, root_dir): 디렉토리 압축shutil.unpack_archive(filename, extract_dir): 압축 해제
5. 주의 사항
- 파일 작업을 수행할 때는 항상 백업을 만들어 두는 것이 좋습니다.
- 디렉토리 삭제 시
shutil.rmtree는 하위 디렉토리와 파일을 모두 삭제하므로 주의가 필요합니다. - 잘못된 경로나 권한 문제로 인해 예외가 발생할 수 있으므로 예외 처리를 적절히 구현해야 합니다.
참조
이 매뉴얼은 Python의 shutil 모듈에 대한 포괄적인 설명을 제공하며, 다양한 예제와 사용법을 통해 사용자에게 깊이 있는 이해를 제공합니다.