Filed under개발정보on3 분 분량

[Python/shutil] 파일 복사하는 방법: shutil.copy, shutil.copyfile, shutil.copy2, shutil.copyfileobj

파이썬의 shutil 라이브러리는 파일과 디렉터리를 복사하는 다양한 기능을 제공한다. 본 글에서는 총 다섯 가지 방법, 즉 shutil.copy, shutil.copyfile, shutil.copy2, shutil.copyfileobj, 그리고 shutil.copytree 메서드를 검토...

파이썬의 shutil 라이브러리는 파일과 디렉터리를 복사하는 다양한 기능을 제공한다. 본 글에서는 총 다섯 가지 방법, 즉 shutil.copy, shutil.copyfile, shutil.copy2, shutil.copyfileobj, 그리고 shutil.copytree 메서드를 검토하겠다. 이들 각각의 차이를 분석하며 그 활용법을 실제 예시를 통해 이해해보도록 하겠다.

shutil.copy

shutil.copy 함수는 파일의 내용을 다른 위치로 복사할 수 있게 해준다. 다음은 그 사용법을 보여주는 간단한 코드 스니펫이다.

import shutil

source = 'source.txt'
destination = 'destination.txt'

shutil.copy(source, destination)

이 예제에서는 source.txt의 내용이 destination.txt로 복사된다. destination.txt가 존재하지 않으면 새로 생성된다.

shutil.copyfile

shutil.copy와는 달리, shutil.copyfile 함수는 파일의 내용만을 복사하며, 권한과 같은 메타데이터는 무시된다. 다음은 예시이다.

import shutil

source = 'source.txt'
destination = 'destination.txt'

shutil.copyfile(source, destination)

이 코드는 source.txt의 내용을 destination.txt로 복사하지만, 파일의 메타데이터는 복사되지 않는다.

shutil.copy2

shutil.copy2 함수는 shutil.copy와 유사한 방식으로 작동하지만, 원본 파일의 메타데이터(타임스탬프와 같은)도 보존한다. 사용법은 다음과 같다.

import shutil

source = 'source.txt'
destination = 'destination.txt'

shutil.copy2(source, destination)

source.txt의 내용과 메타데이터가 destination.txt로 복사된다.

shutil.copyfileobj

shutil.copyfileobj 함수는 파일 개체의 내용을 다른 파일 개체로 복사하는 데 사용된다. 실용적인 예시는 다음과 같다.

import shutil

with open('source.txt', 'rb') as src, open('destination.txt', 'wb') as dest:
    shutil.copyfileobj(src, dest)

이 코드는 source.txt의 내용을 읽어와 destination.txt로 기록한다.

shutil.copytree

shutil.copytree 함수는 전체 디렉터리 트리를 복사하는 데 사용된다. 예시는 다음과 같다.

import shutil

source_dir = 'source_directory'
destination_dir = 'destination_directory'

shutil.copytree(source_dir, destination_dir)

이 코드는 source_directory의 전체 내용을 destination_directory로 복사한다.

비교 테이블

함수 내용 복사 권한 복사 메타데이터 복사 파일 개체 사용 대상이 디렉터리 일 수 있음
shutil.copy 아니요 아니요
shutil.copyfile 아니요 아니요 아니요 아니요
shutil.copy2 아니요
shutil.copyfileobj 아니요 아니요 아니요
shutil.copytree 아니요

Python의 shutil 라이브러리는 다양한 파일과 디렉터리를 복사하는 함수를 제공한다. 이들의 차이점을 이해하면 효율적인 파일 관리를 할 수 있다.


자주 묻는 질문

  1. shutil.copy와 shutil.copy2의 주요 차이점은 무엇인가? shutil.copy는 내용과 권한을 복사하지만, shutil.copy2는 타임스탬프와 같은 메타데이터도 포함한다.

  2. shutil.copytree는 중첩된 디렉터리를 복사할 수 있나요? 그렇다, shutil.copytree는 중첩된 디렉터리와 파일을 모두 포함하여 전체 디렉터리 트리를 재귀적으로 복사한다.

  3. shutil은 심볼릭 링크를 어떻게 처리하나요? 기본적으로 심볼릭 링크를 따른다. 심볼릭 링크를 보존하려면 shutil.copytree에서 symlinks=True 인자를 사용해보자.

  4. shutil.copyfileobj는 원격 파일 간에 복사할 수 있나요? 파일 개체와 함께 작동하므로, Python에서 파일 개체로 표현될 수 있는 경우 원격 파일 간에 복사할 수 있다.

  5. shutil를 사용하여 특정 확장자를 가진 파일을 복사할 수 있나요? 그렇다, shutil과 함께 Python의 glob 모듈을 사용하여 특정 확장자를 가진 파일을 필터링하고 이에 맞게 복사할 수 있다.

모든 아티클로 돌아가기