개발일지
10/1 - 최하위 폴더 검색하기.....
wandering developer
2024. 10. 1. 23:00
최하위 폴더에 파일들이 있을때 최하위 폴더를 찾는 방법은 파이썬에서 작성할때는
아래 코드를 사용하면 최하위 폴더를 바로 찾을 수 있다.
for root, dirs, files in os.walk(source_folder):
# dirs가 비어있는 경우 최하위 폴더임을 의미
if not dirs:
그래서 특정 파일만 옮기고 싶을때 혹은 특정 조건에 부합하는 파일만 옮기고 싶을때 아래 코드를 사용하면 된다.
import os
import shutil
def move_files_from_source_to_destination(source_folder, destination_folder):
# os.walk를 사용해 source_folder의 모든 폴더와 파일을 순회
for root, dirs, files in os.walk(source_folder):
# dirs가 비어있는 경우 최하위 폴더임을 의미
if not dirs:
# 현재 폴더에 파일이 있는 경우
for file in files:
source_file_path = os.path.join(root, file)
destination_file_path = os.path.join(destination_folder, file)
# 파일을 목적지 폴더로 이동
print(f'Moving file: {source_file_path} to {destination_file_path}')
shutil.move(source_file_path, destination_file_path)
# 예시 사용
source_folder = '/path/to/source_folder'
destination_folder = '/path/to/destination_folder'
move_files_from_source_to_destination(source_folder, destination_folder)
반응형