우선 필요한 모듈을 임포트해준다.
import os
import shutil
import time
폴더 안에 있는 모든 하위 파일(서브폴더의 파일 포함)을 읽어 리스트로 반환하는 함수를 정의한다. 반복문과 재귀 함수를 이용해서 하위 폴더의 파일까지 모두 접근한다.
def read_all_file(path):
output = os.listdir(path)
file_list = []
for i in output:
if os.path.isdir(path+"/"+i):
file_list.extend(read_all_file(path+"/"+i))
elif os.path.isfile(path+"/"+i):
file_list.append(path+"/"+i)
return file_list
def copy_all_file(file_list, new_path):
for src_path in file_list:
file = src_path.split("/")[-1]
shutil.copyfile(src_path, new_path+"/"+file)
print("파일 {} 작업 완료".format(file))
# 작업한 파일명 출력
start_time = time.time() # 작업 시작 시간
src_path = "C:/test" # 기존 폴더 경로
new_path = "C:/test_merge" # 옮길 폴더 경로
file_list = read_all_file(src_path)
copy_all_file(file_list, new_path)
print("=" * 40)
print("러닝 타임 : {}".format(time.time() - start_time)) # 총 소요시간 계산