[Python] 파일 복사하기 (shutil.copy)
파이썬으로 파일을 복사하는 함수인 shutil.copy 의 사용법을 예제로 알아보려고 합니다.
아래 내용은 파이썬 공식 문서를 참고하여 작성하였습니다.
파이썬 shutil 관련 공식 문서
한국어 공식 문서: docs.python.org/ko/3/library/shutil.html
shutil — 고수준 파일 연산 — Python 3.9.2 문서
shutil — 고수준 파일 연산 소스 코드: Lib/shutil.py shutil 모듈은 파일과 파일 모음에 대한 여러 가지 고수준 연산을 제공합니다. 특히, 파일 복사와 삭제를 지원하는 함수가 제공됩니다. 개별 파일
docs.python.org
영어 공식 문서: docs.python.org/3/library/shutil.html
shutil — High-level file operations — Python 3.9.2 documentation
shutil — High-level file operations Source code: Lib/shutil.py The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on i
docs.python.org
파일을 다루기 위해서는 파이썬에서 제공하는 "shutil 모듈"을 사용해야합니다.
shutil을 통해 파일의 복사, 삭제, 이동, 권한설정 등이 가능합니다.
예제를 통해 어떻게 사용하는 지 알아보도록 하겠습니다.
#현재 작업중인 디렉토리에 있는 파일/디렉토리을 복사하는 법
디렉토리의 경로를 다룰때는 os 모듈을 사용하는데요, 관련 내용은 여기서 볼 수 있습니다.
shutil.copy를 통해 파일 또는 디렉토리를 복사할 수 있습니다.
import os
import shutil
#현재 작업중인 디렉토리의 경로를 받아옵니다
current_working_directory = os.getcwd()
#현재 작업중인 디렉토리의 경로 + 만들고자 하는 파일의 이름
source_file = os.path.join(current_working_directory, "SOURCE")
target_file = os.path.join(current_working_directory, "TARGET")
#source file을 복사하여 target file을 만듭니다.
shutil.copy(source_file, target_file)
위와 같이 파일을 복사하는 함수는 아래와 같은 형식으로 호출해 줄 수 있습니다.
shutil.copy(원본 경로, 대상 경로)
shutil.copy(src, dst, *, follow_symlinks=True)¶
os — Miscellaneous operating system interfaces — Python 3.9.2 documentation
os — Miscellaneous operating system interfaces Source code: Lib/os.py This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.
docs.python.org
여기까지가 파이썬으로 파일 복사하는 방법이었습니다. 보다 여러가지 예제들은 차차 추가할 예정이니, 혹시 궁금하신 부분은 문의 부탁드립니다:)