[파이썬] shutil `shutil.copytree()`와 파일 충돌 처리하기

파이썬의 shutil 모듈에는 디렉토리를 재귀적으로 복사하는 함수인 shutil.copytree()가 있습니다. 이 함수를 사용하면 간편하게 디렉토리 전체를 복사할 수 있습니다. 하지만 때로는 복사하는 중에 이미 동일한 이름의 파일이나 디렉토리가 존재하는 경우 충돌 문제가 발생할 수 있습니다. 이러한 충돌을 처리하는 방법에 대해 알아보겠습니다.

1. shutil.copytree() 함수 사용하기

shutil.copytree() 함수를 사용하여 디렉토리를 복사하는 방법은 매우 간단합니다. 다음은 이 함수의 사용 예시입니다.

import shutil

# 소스 디렉토리와 목적 디렉토리 경로
src_dir = 'path/to/source/directory'
dst_dir = 'path/to/destination/directory'

# 디렉토리 복사
shutil.copytree(src_dir, dst_dir)

위의 코드는 src_dir 경로의 디렉토리를 dst_dir 경로로 복사합니다.

2. 파일 충돌 처리하기

하지만 실제로는 이미 동일한 이름의 파일이나 디렉토리가 존재하는 경우, shutil.copytree() 함수는 FileExistsError 예외를 발생시킵니다. 이를 처리하기 위해서는 몇 가지 방법이 있습니다.

2.1. 예외 처리하기

try-except 문을 사용하여 FileExistsError 예외를 처리할 수 있습니다. 다음은 이 방법의 예시입니다.

import shutil

src_dir = 'path/to/source/directory'
dst_dir = 'path/to/destination/directory'

try:
    shutil.copytree(src_dir, dst_dir)
except FileExistsError:
    print("Destination directory already exists.")

위의 코드는 dst_dir 경로에 이미 디렉토리가 존재할 경우, 예외가 발생하여 “Destination directory already exists”라는 메시지를 출력합니다.

2.2. 기존 디렉토리 삭제하기

다른 방법으로는 shutil.rmtree() 함수를 사용하여 기존의 디렉토리를 삭제한 후에 복사하는 방법이 있습니다. 다음은 이 방법의 예시입니다.

import shutil
import os

src_dir = 'path/to/source/directory'
dst_dir = 'path/to/destination/directory'

if os.path.exists(dst_dir):
    shutil.rmtree(dst_dir)  # 기존 디렉토리 삭제

shutil.copytree(src_dir, dst_dir)

위의 코드는 dst_dir 경로에 이미 디렉토리가 존재할 경우, 해당 디렉토리를 먼저 삭제한 후에 복사를 수행합니다.

결론

shutil.copytree() 함수를 사용하여 디렉토리를 복사하는 경우, 이미 동일한 이름의 파일이나 디렉토리가 존재하는 경우 예외가 발생합니다. 이러한 충돌을 처리하기 위해서는 예외 처리 방법이나 기존 디렉토리 삭제 방법을 사용할 수 있습니다. 위의 예시 코드를 참고하여 파일 충돌 처리를 적절하게 처리해보세요.