[Python] 파일과 디렉토리 복사,이동/shutil 모듈


shutil 모듈은 기본으로 설치되어 있는 파이썬 내장 라이브러리이기 때문에 따로 설치할 필요가 없습니다.


파일 복사

파일 복사를 위해서는 copy() 함수를 사용합니다. copy(복사할 파일, 복사 위치) 형식으로 작성합니다.

import shutil

shutil.copy('test1.txt','..\\shutil_test') #파일 복사

 

복사 전 shutil_test 폴더
복사 후 shutil_test 폴더

 

전체 디렉토리를 복사하는 것은 copytree() 함수를 사용합니다. copytree(복사할 디렉토리, 복사위치) 형식으로 작성합니다.

shutil.copytree('D:\\python_study\\os_test','..\\copy_file') #파일 복사

 

copytree() 사용하여 디렉토리 복사

 

파일 이동

파일을 이동시키기 위해 move() 함수를 사용합니다. move(이동할 파일,이동 위치) 형식으로 작성합니다.

#os_test에 있는 read_cartoon.txt파일을 'D:\python_study'로 이동
shutil.move('read_cartoon.txt','D:\\python_study')

 

read_cartoon.txt 파일 이동