관리 메뉴

개발자비행일지

파이썬 폴더 정리 스크립트 본문

▶ Python

파이썬 폴더 정리 스크립트

Cyber0946 2023. 1. 23. 11:42

파이썬을 이용해서, 원하는 경로의 모든 파일을 확장자 별로 분류하여, 폴더를 만들어 준뒤 TOP라는 상위 폴더에 통합해 주는 스크립트 

import os
import shutil

def classify_and_move_files(desktop_dir, file_types):
    # Create a dictionary to store the file types as keys and the corresponding folder names as values
    folders = {file_type: file_type.strip('.') + 's' for file_type in file_types}
    print(folders)

    # Create the TOP folder
    top_folder = os.path.join(desktop_dir, "TOP")
    if not os.path.exists(top_folder):
        os.mkdir(top_folder)

    # Iterate through all the items in the desktop directory
    for item in os.listdir(desktop_dir):
        # Check if the item is a folder and not the route folder
        if os.path.isdir(os.path.join(desktop_dir, item)) and item != "TOP":
            # Move the folder into the route folder
            shutil.move(os.path.join(desktop_dir, item), top_folder)

    # Create the Folders
    for file_type in file_types:
        folder_path = os.path.join(desktop_dir, folders[file_type])
        if not os.path.exists(folder_path):
            os.mkdir(folder_path)

    # Move files into the corresponding folders
    for file_name in os.listdir(desktop_dir):
        for file_type in file_types:
            if file_name.endswith(file_type):
                shutil.move(os.path.join(desktop_dir, file_name), os.path.join(desktop_dir, folders[file_type]))
                break

# Set the directory you want to classify
download_dir = "C:\\Users\\user\\Downloads"
desktop_dir = "C:\\Users\\user\\Desktop"

# Get the list of file types you want to classify
file_types = ['.exe', '.pdf', '.docx', '.jpg', '.png','.pptx','.hwp']

# Call the classify_and_move_files method
classify_and_move_files(desktop_dir, file_types)