본문 바로가기

코딩/파이썬 기초

파이썬 튜토리얼 045. shutil 라이브러리의 copy 함수로 파일 복사

python - shutil - copy

 

파이썬 표준 라이브러리 shutil의 copy() 함수를 이용해 임의 파일을 복사할 수 있다.

 

shutil의 copy() 함수는 shutil의 copyfile() 함수와 그 사용 방법이 유사하나 파일이 복사될 디렉토리 만을 지정해도 파일 복사가 가능한 차이점이 있다.

 

<코드 1>

import shutil

ret = shutil.copy('main.py', 'main_copy.py')

print(ret)

 

<코드 1>을 실행하면 main.py 파일이 저정되어 있는 디렉토리(폴더)에 main_copy.py 파일이 생성된다.

 

 

shutil.copy() 함수는 shutil.copyfile() 함수와 동일하게 복사된 파일 정보를 반환한다.

아래는 print(ret) 실행의 결과이다.

 

main_copy.py

 

<코드 2>

import shutil

ret = shutil.copy('main.py', 'main.py')

print(ret)

 

<코드 2>와 같이 복사 파일의 이름과 확장자가 원본 파일과 동일하면 shutil.copyfile() 함수와 동일하게 오류가 발생한다.

 

Traceback (most recent call last):
  File "C:\MyPrograms\py39x\src\main.py", line 5, in <module>
    ret = shutil.copy('main.py', 'main.py')
  File "C:\Python39\lib\shutil.py", line 418, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Python39\lib\shutil.py", line 244, in copyfile
    raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
shutil.SameFileError: 'main.py' and 'main.py' are the same file

 

<코드 3>

import shutil

ret = shutil.copy('main.py', 'copied')

print(ret)

 

<코드 3>과 같이 shutil.copy() 함수가 shutil.copyfile() 함수와 다른 점은 두번째 전달인자로 파일이 복사될 디렉토리 만을 지정해도 오류가 발생하지 않고 지정한 디렉토리에 파일이 복사된다는 것이다. 이 경우 복사되는 파일 이름과 확장자는 원본 파일과 같다.

 

 

<코드 4>

import shutil

ret = shutil.copy('main.py', 'new_copied/')

print(ret)

 

shutil.copy() 함수도 shutil.copyfile() 함수와 같이 존재하지 않는 디렉토리를 지정하면 오류가 발생한다.

 

Traceback (most recent call last):
  File "C:\MyPrograms\py39x\src\main.py", line 5, in <module>
    ret = shutil.copy('main.py', 'new_copied/')
  File "C:\Python39\lib\shutil.py", line 418, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Python39\lib\shutil.py", line 264, in copyfile
    with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
OSError: [Errno 22] Invalid argument: 'new_copied/'

 

<코드 5>

import shutil
import os.path

copy_path = 'copied'
if os.path.exists(copy_path):
    ret = shutil.copy('main.py', copy_path)
else:
    print('no directory')

 

<코드 5>는 os.path 라이브러리의 exists() 함수를 이용해 파일을 복사하는 코드가 실행되기 전, 디렉토리가 존재하는지를 확인한다.