파이썬 표준 라이브러리 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/'
'코딩 > 파이썬 기초' 카테고리의 다른 글
파이썬 튜토리얼 046. glob 라이브러리의 glob() 함수로 원하는 이름의 디렉토리 및 파일 리스트 얻기 (0) | 2021.10.13 |
---|---|
파이썬 튜토리얼 045. shutil 라이브러리의 copy 함수로 파일 복사 (0) | 2021.09.17 |
파이썬 튜토리얼 043. Iterators와 Generators에 대한 예제 (0) | 2021.09.11 |
파이썬 튜토리얼 042. 클래스의 상속과 supper 클래스 (0) | 2021.09.03 |
파이썬 튜토리얼 041. 클래스 정의 및 클래스 attributes (0) | 2021.08.24 |