본문 바로가기

코딩/파이썬 기초

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

python - shutil - copyfile

 

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

 

<코드 1>

import shutil

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

print(ret)

 

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

 

 

shutil.copyfile() 함수는 복사된 파일 정보를 반환한다. 아래는 print(ret) 실행의 결과이다.

 

main_copy.py

 

<코드 2>

import shutil

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

print(ret)

 

<코드 2>와 같이 복사된 파일의 확장자는 원본과 동일하지 않게 설정할 수 있다.

 

 

<코드 3>

import shutil

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

print(ret)

 

<코드 3>과 같이 복사 파일의 이름과 확장자가 원본 파일과 동일하면 오류가 발생한다.

 

Traceback (most recent call last):
  File "C:\MyPrograms\py39x\src\main.py", line 5, in <module>
    ret = shutil.copyfile('main.py', 'main.py')
  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

 

<코드 4>

import shutil

ret = shutil.copyfile('main.py', 'copied/main.py')

print(ret)

 

<코드 4>는 다른 디렉토리(폴더)로 파일을 복사하는 예이다.

다른 디렉토리에 파일을 복사할 때는 복사 파일의 이름과 확장자가 원본 파일과 동일해도 오류가 발생하지 않는다.

 

 

아래는 shutil.copyfile() 함수의 반환 값이다.

 

copied/main.py

 

<코드 5>

import shutil

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

print(ret)

 

<코드 5>와 같이 존재하지 않는 디렉토리 new_copied에 파일 복사를 시도하는 경우 오류가 발생한다.

 

Traceback (most recent call last):
  File "C:\MyPrograms\py39x\src\main.py", line 5, in <module>
    ret = shutil.copyfile('main.py', 'new_copied/main.py')
  File "C:\Python39\lib\shutil.py", line 264, in copyfile
    with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: 'new_copied/main.py'

 

<코드 6>

import shutil

ret = shutil.copyfile('main.py', 'copied/')

print(ret)

 

<코드 6>과 같이 복사 파일이 생성되는 디렉토리는 지정하였으나 복사 파일의 이름과 확장자를 설정하지 않아도 오류가 발생한다.

 

Traceback (most recent call last):
  File "C:\MyPrograms\py39x\src\main.py", line 5, in <module>
    ret = shutil.copyfile('main.py', 'copied/')
  File "C:\Python39\lib\shutil.py", line 264, in copyfile
    with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'copied/'