[파이썬] shutil 다양한 파일 시스템과의 호환성

파이썬의 shutil 모듈은 파일 및 디렉토리 작업을 수행하는 함수들을 제공합니다. 이 모듈은 여러 가지 파일 시스템과의 호환성을 지원하며, 파일 및 디렉토리를 안전하고 효율적으로 조작할 수 있는 많은 기능들을 제공합니다.

파일과 디렉토리 복사

shutil 모듈은 파일이나 디렉토리를 다른 위치로 복사하는 기능을 제공합니다. copy() 함수는 파일을 복사하고, copy2() 함수는 파일의 메타데이터도 함께 복사합니다. copytree() 함수는 디렉토리를 재귀적으로 복사하며, 하위 디렉토리와 파일도 모두 복사됩니다.

import shutil

shutil.copy('source.txt', 'destination.txt')
shutil.copy2('source.txt', 'destination.txt')
shutil.copytree('source_dir', 'destination_dir')

디렉토리 삭제

shutil 모듈은 디렉토리를 삭제하는 함수도 제공합니다. rmtree() 함수는 재귀적으로 디렉토리와 하위 파일을 모두 삭제합니다.

import shutil

shutil.rmtree('directory_to_delete')

파일 압축 및 해제

shutil 모듈은 파일과 디렉토리를 압축하고 해제하는 기능도 제공합니다. make_archive() 함수는 압축 파일을 생성하고, unpack_archive() 함수는 압축 파일을 해제합니다. shutil 모듈은 다양한 압축 형식을 지원하며, zip, tar, gztar, bztar, xztar, targz, tarbz2, tarxz 형식의 압축 파일들을 다룰 수 있습니다.

import shutil

shutil.make_archive('archive', 'zip', 'source_dir')
shutil.unpack_archive('archive.zip', 'destination_dir')

파일 정보 확인

shutil 모듈은 파일 및 디렉토리에 대한 정보를 확인하는 함수들도 제공합니다. stat() 함수는 파일의 메타데이터를 반환하고, getsize() 함수는 파일의 크기를 반환합니다.

import shutil

info = shutil.stat('filename.txt')
size = shutil.getsize('filename.txt')

shutil 모듈은 다양한 파일 시스템과의 호환성을 제공하여 파일 및 디렉토리 조작을 보다 효율적으로 수행할 수 있도록 도와줍니다. shutil 모듈의 다양한 함수들을 활용하여 파일 및 디렉토리 작업을 간편하고 안전하게 수행할 수 있습니다.