본문 바로가기

공부/code

[Python] 폴더 안의 모든 하위 파일 복사해서 하나의 폴더로 합치기 코드 (Copy Files from Multiple Subfolders to a Merged Folder)

 

폴더 안의 모든 하위 파일 복사해서 하나의 폴더로 합치기

Copy All Files from Multiple Subfolders to a Merged Folder

 

 

개요 

 

최근 폴더 안의 모든 하위 파일들(서브 폴더의 파일 포함)을 복사해서 또다른 하나의 폴더로 합쳐야 할 일이 있었다.

 

구글링해보니 폴더에서 *를 검색해서 모든 하위파일들을 찾아 복사해서 옮기라고 하는 글이 많았지만, 난 하위폴더와 파일 개수가 너무 많아서 노가다 단순반복 작업이었다. 마침 요즘 파이썬 입문강의를 듣고 공부한 내용을 바탕으로 실습을 해보고 싶어져서 단순 반복 작업을 대신해주는 파이썬 코드를 만들어 보았다. 

 

 

 


코드 짜기

 

1. 우선 필요한 모듈을 임포트해준다.

import os
import shutil

 

2. 폴더 안에 있는 모든 하위 파일(서브폴더의 파일 포함)을 읽어 리스트로 반환하는 함수를 정의한다. 반복문과 재귀 함수를 이용해서 하위 폴더의 파일까지 모두 접근한다. 

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

 

3. 폴더 내의 모든 하위 파일들을 새로운 경로로 복사하는 함수를 정의한다. 

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)

 

4. 정의한 함수들을 실행하여 폴더 안의 모든 하위 파일들(서브 폴더의 파일 포함)을 복사해서 또다른 하나의 폴더로 합친다. 참고로 src_path에는 기존 폴더의 경로를 적어주고, new_path에는 파일들을 옮길 새로운 폴더 경로를 적어준다. 

src_path = "기존 폴더 경로" 
new_path = "옮길 폴더 경로"

file_list = read_all_file(src_path)
copy_all_file(file_list, new_path)

 


최종코드 

 

1. 가볍게 test폴더와 test_merged 폴더를 만들어서 실행해보았다.

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)) # 총 소요시간 계산

 

2. 코드 실행 전 test 폴더와 test_merged 폴더 

test 폴더 안에 여러개의 하위 폴더와 파일이 들어있음
test 폴더의 모든 하위파일들이 옮겨질 test_merged 폴더

 

3. 코드 실행시 출력된 결과

파일 1.txt 작업 완료
파일 1.xlsx 작업 완료
파일 1-1.ppt 작업 완료
파일 1-1.txt 작업 완료
파일 1-1.xls 작업 완료
파일 1-2.txt 작업 완료
파일 10.txt 작업 완료
파일 2.txt 작업 완료
파일 2-1.doc 작업 완료
파일 2-1.jpg 작업 완료
파일 2-1.txt 작업 완료
파일 2-2.txt 작업 완료
파일 2-2.xlsx 작업 완료
파일 3.txt 작업 완료
파일 4.txt 작업 완료
파일 5.txt 작업 완료
파일 6.txt 작업 완료
파일 7.txt 작업 완료
파일 8.txt 작업 완료
파일 9.txt 작업 완료
========================================
러닝 타임 : 0.04274916648864746

 

4. 코드 실행 후 test_merged 폴더 

test 폴더의 모든 하위 파일들(서브폴더의 파일들 포함)이 test_merged 폴더로 복사되어 옮겨진 것을 확인할 수 있다. 

 

반응형