본문 바로가기
프로그래밍/Python

[Python] shutil을 이용한 파일 복사(File Copy), 폴더 복사(Folder Copy) 하기 (feat. distutils)

by 부자 꽁냥이 2022. 5. 7.

파이썬(Python)을 이용하면 파일과 폴더를 복사할 수 있다. shutil이라는 모듈을 이용하면 된다.

 

이번 포스팅에서는 파이썬(Python) 내장 모듈인 shutil를 이용하여 파일과 폴더를 복사하는 방법을 알아본다.

 

- 목차 -

1. shutil을 이용한 파일 복사

2. shutil을 이용한 폴더 복사 (feat. distutils)


   1. shutil을 이용한 파일 복사

shutil.copy, shutil.copyfile, shutil.copy2를 이용하면 파일을 복사할 수 있다. 이들의 사용법은 첫 번째 인자에는 복사할 파일 위치, 두 번째 인자에는 복사 위치 + 파일명을 넣어주면 된다. 이때 기존 파일과 동일한 명으로 복사 파일명을 지정했다면 덮어쓰기(Overwriting)가 된다.

 

아래 코드를 참고하자.

 

import shutil
from_file_path = '../test_folder/folder1/sample_01.txt' # 복사할 파일
to_file_path = '../test_folder/folder1/sample_02.txt' # 복사 위치 및 파일 이름 지정
shutil.copyfile(from_file_path, to_file_path)
# 또는 shutil.copy(from_file_path, to_file_path)
# 또는 shutil.copy2(from_file_path, to_file_path)

 

참고로 shutil.copyfile과 shutil.copy는 메타 정보를 복사하지 않으므로 수정한 날짜가 복사한 시점이 된다(아래 왼쪽 그림). 하지만 shutil.copy2는 메타 정보를 복사하므로 수정한 날짜가 복사한 파일의 수정한 날짜와 동일하다(아래 오른쪽 그림).

 

shutil.copy(shutil.copyfile)과 shutil.copy2의 차이


   2. shutil을 이용한 폴더 복사 (feat. distutils)

shutil.copytree를 사용하면 폴더를 복사할 수 있다. 사용법은 파일 복사와 동일하게 첫 번째 인자에 복사 폴더와 두 번째 인자에 복사 위치+폴더명을 지정하면 된다.

 

import shutil
from_file_path = '../test_folder/folder1' # 복사할 폴더
to_file_path = '../test_folder/folder2' # 복사 위치
shutil.copytree(from_file_path, to_file_path)

 

주의할 부분은 폴더명이 기존에 있다면 아래와 같은 오류가 생긴다. 즉 덮어쓰기가 안 되는 것이다.

 

shutil.copytree는 덮어 쓰기가 안된다.

복사할 파일을 기존 폴더에 덮어쓰고 싶다면 내장 모듈인 distutils.dir_util의 copy_tree를 사용하면 된다. 사용법은 shutil.copytree와 동일하다.

 

from distutils.dir_util import copy_tree
from_file_path = '../test_folder/folder1' # 복사할 폴더
to_file_path = '../test_folder/folder2' # 복사 위치
copy_tree(from_file_path, to_file_path)

 

 


댓글