코린이/코딩 기초 & 알고리즘 공부
[python] shutil 모듈로 파일 복사 및 이동하기
anweh
2020. 10. 19. 11:22
shutil은 파일을 복사 및 이동할 때 유용한 모듈이다.
작업중이던 파일을 일단 복사해서 새 경로에 저장해서 원본을 유지하고 싶을 때 코드 중간에 파일 복사 및 이동을 삽입하게 된다. (개인적으론 그랬음)
코드는 다음과 같다.
shutil.copy(src, dst) & shutil.move(src, dst)
import os
import shutil
path = 'C:/Users/user/Desktop/folder/'
files = os.listdir(path)
new_path = 'C:/Users/user/Desktop/folder/images/'
if not os.path.exists(new_path):
os.mkdir(new_path)
# move
for file in files:
if 'jpg' in file:
shutil.move(path + file, new_path + file)
print('{} has been moved to new folder!'.format(file))
# copy
for file in files:
if 'pdf' in file:
shutil.copy(path + file, new_path + file)
print('{} has been copied in new folder!'.format(file))
src라는 이름의 파일을 dst로 복사 및 이동하게 된다.
만약 해당 코드를 실행할 때 현재 경로가 해당 파일이 있는 곳이 아니라면,
src에는 경로 + 파일명을 적어줘야한다. dst에도 마찬가지다.
콘솔 실행 결과
짠