[파이썬] shutil로 대용량 파일/디렉토리 작업하기

파이썬의 shutil 모듈을 사용하면 대용량 파일이나 디렉토리를 효과적으로 다룰 수 있습니다. shutil은 파일 및 디렉토리 조작을 단순화하는 다양한 함수를 제공합니다. 이 글에서는 shutil을 사용하여 대용량 파일/디렉토리 작업을 수행하는 방법에 대해 알아보겠습니다.

1. 파일 복사하기

shutilcopy 함수를 사용하여 파일을 복사할 수 있습니다. 다음은 source_file에서 destination_file로 파일을 복사하는 예제입니다.

import shutil

source_file = "path/to/source/file"
destination_file = "path/to/destination/file"

shutil.copy(source_file, destination_file)

위 코드에서는 source_filedestination_file로 복사하고 있습니다. shutil.copy 함수를 사용하면 파일의 내용을 모두 복사하여 새로운 파일을 생성합니다.

2. 디렉토리 복사하기

shutilcopytree 함수를 사용하면 디렉토리 전체를 복사할 수 있습니다. 다음은 source_dir에서 destination_dir로 디렉토리를 복사하는 예제입니다.

import shutil

source_dir = "path/to/source/directory"
destination_dir = "path/to/destination/directory"

shutil.copytree(source_dir, destination_dir)

해당 코드에서는 source_dir 전체 내용을 destination_dir로 복사합니다. 디렉토리가 비어 있지 않은 경우에도 모든 파일 및 하위 디렉토리가 재귀적으로 복사됩니다.

3. 파일 이동하기

shutilmove 함수를 사용하면 파일을 이동할 수 있습니다. 다음은 source_filedestination_file로 이동하는 예제입니다.

import shutil

source_file = "path/to/source/file"
destination_file = "path/to/destination/file"

shutil.move(source_file, destination_file)

위 코드에서는 source_filedestination_file로 이동합니다. shutil.move 함수를 사용하여 파일을 이동하면 동일한 파일에 대해 임시 파일을 사용하여 안전하게 이동합니다.

4. 디렉토리 이동하기

shutilmove 함수를 사용하여 디렉토리를 이동할 수도 있습니다. 다음은 source_dirdestination_dir로 이동하는 예제입니다.

import shutil

source_dir = "path/to/source/directory"
destination_dir = "path/to/destination/directory"

shutil.move(source_dir, destination_dir)

해당 코드에서는 source_dir 전체 내용을 destination_dir로 이동합니다. shutil.move 함수를 사용하여 디렉토리를 이동하면 동일한 디렉토리에 대해 임시 디렉토리를 사용하여 안전하게 이동합니다.

5. 파일/디렉토리 삭제하기

shutilrmtree 함수를 사용하면 파일이나 디렉토리 전체를 삭제할 수 있습니다. 다음은 path로 지정된 파일이나 디렉토리를 삭제하는 예제입니다.

import shutil

path = "path/to/file/or/directory"

shutil.rmtree(path)

해당 코드에서는 path에 지정된 파일이나 디렉토리를 완전히 삭제합니다. 삭제할 때는 조심해야 하므로 신중하게 사용해야 합니다.

마무리

이 글에서는 shutil 모듈을 사용하여 대용량 파일 및 디렉토리를 다루는 방법을 알아보았습니다. shutil을 사용하면 파일 복사, 디렉토리 복사, 파일 이동, 디렉토리 이동, 파일/디렉토리 삭제 등 다양한 작업을 신속하고 효과적으로 수행할 수 있습니다. shutil 모듈의 함수들을 자세히 살펴보고, 필요에 맞게 사용해 보시기 바랍니다.