본문으로 바로가기

파일 복사하기 shutil.copy() 와 shutil.copy2()

해당 경로에 원본 파일명과 동일한 파일을 복사합니다. (덮어쓰기 가능)

shutil.copy() 와 shutil.copy2() 의 차이점은, copy2() 는 메타정보까지 복사합니다. 

다음 예로 copy() 는 src 파일 과 dst 파일의 mtime이 차이가 있습니다. (메타정보)

import os
import shutil
import datetime

path = os.path.dirname(os.path.abspath(__file__))
fname = 'file.txt'
dir_name = 'test_dir'
copy_dir_name = 'copy'

os.chdir(dir_name)
mtime = os.path.getmtime(fname)
mtime = datetime.datetime.fromtimestamp(mtime).replace(microsecond=0)
print(fname, mtime)

shutil.copy(fname, 'copy')

os.chdir(copy_dir_name)
mtime = os.path.getmtime(fname)
mtime = datetime.datetime.fromtimestamp(mtime).replace(microsecond=0)
print(fname, mtime)
더보기
file.txt 2020-06-30 15:45:01
file.txt 2020-06-30 15:58:27

 

copy2()의 mtime 은 동일합니다.

import os
import shutil
import datetime

path = os.path.dirname(os.path.abspath(__file__))
fname = 'file.txt'
dir_name = 'test_dir'
copy_dir_name = 'copy'

os.chdir(dir_name)
mtime = os.path.getmtime(fname)
mtime = datetime.datetime.fromtimestamp(mtime).replace(microsecond=0)
print(fname, mtime)

shutil.copy2(fname, 'copy')

os.chdir(copy_dir_name)
mtime = os.path.getmtime(fname)
mtime = datetime.datetime.fromtimestamp(mtime).replace(microsecond=0)
print(fname, mtime)
더보기
file.txt 2020-06-30 15:45:01
file.txt 2020-06-30 15:45:01

 

디렉터리 복사 shutil.copytree()

shutil.copytree() 는 하위항목을 포함한 디렉터리를 복사합니다.

import os
import shutil

path = os.path.dirname(os.path.abspath(__file__))
dir_name = 'data'
copy_dir = 'data2'

print(*os.listdir(dir_name))
shutil.copytree(dir_name, copy_dir)
print(*os.listdir(copy_dir))
더보기
a b
a b

 

동일한 경로가 있을 경우 에러 발생

Traceback (most recent call last):
  File "c:/Users/Desktop/python/os_/ex7.py", line 11, in <module>
    shutil.copytree(dir_name, copy_dir)
  File "C:\ProgramData\Anaconda3\envs\py36\lib\shutil.py", line 321, in copytree
    os.makedirs(dst)
  File "C:\ProgramData\Anaconda3\envs\py36\lib\os.py", line 220, in makedirs
    mkdir(name, mode)
FileExistsError: [WinError 183] 파일이 이미 있으므로 만들 수 없습니다: 'data2'

 

경로가 존재하지 않으면 디렉터리 생성하여 복사 진행

import os
import shutil

path = os.path.dirname(os.path.abspath(__file__))
dir_name = 'data'
print(*os.listdir(dir_name))

copy_dir = 'copy/data'
shutil.copytree(dir_name, copy_dir)
print(*os.listdir(copy_dir))
더보기
a b
a b