DEV Community

Brad
Brad

Posted on

Python File Organization Script: Auto-Sort Downloads Folder

Python File Organization Script: Auto-Sort Downloads Folder

If your Downloads folder looks like digital chaos, Python can automate the cleanup in seconds.

The Solution

import os
import shutil
from pathlib import Path
from datetime import datetime

FILE_TYPES = {
    'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp'],
    'Documents': ['.pdf', '.doc', '.docx', '.txt', '.xlsx', '.pptx'],
    'Videos': ['.mp4', '.avi', '.mkv', '.mov', '.wmv'],
    'Audio': ['.mp3', '.wav', '.flac', '.aac', '.ogg'],
    'Archives': ['.zip', '.rar', '.7z', '.tar', '.gz'],
    'Code': ['.py', '.js', '.html', '.css', '.java', '.json'],
}

def organize_folder(folder_path: str, dry_run: bool = True):
    folder = Path(folder_path)
    moved = []

    for file_path in folder.iterdir():
        if file_path.is_dir():
            continue

        ext = file_path.suffix.lower()
        category = 'Other'

        for cat, extensions in FILE_TYPES.items():
            if ext in extensions:
                category = cat
                break

        dest_dir = folder / category
        dest_dir.mkdir(exist_ok=True)
        dest_file = dest_dir / file_path.name

        if dry_run:
            print(f"Would move: {file_path.name} to {category}/")
        else:
            shutil.move(str(file_path), str(dest_file))
            print(f"Moved: {file_path.name} to {category}/")
            moved.append(str(file_path))

    return len(moved)

# Usage:
# organize_folder(str(Path.home() / 'Downloads'), dry_run=True)   # Preview
# organize_folder(str(Path.home() / 'Downloads'), dry_run=False)  # Execute
Enter fullscreen mode Exit fullscreen mode

Run From Command Line

python organize.py ~/Downloads         # Preview (safe)
python organize.py ~/Downloads --go    # Actually move files
Enter fullscreen mode Exit fullscreen mode

Add --go flag to execute:

import sys
folder = sys.argv[1] if len(sys.argv) > 1 else str(Path.home() / 'Downloads')
dry_run = '--go' not in sys.argv
organize_folder(folder, dry_run=dry_run)
Enter fullscreen mode Exit fullscreen mode

Watch Folder in Real-Time

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class AutoOrganizer(FileSystemEventHandler):
    def __init__(self, folder):
        self.folder = folder

    def on_created(self, event):
        if not event.is_directory:
            time.sleep(1)  # Wait for file write to complete
            file_path = Path(event.src_path)
            ext = file_path.suffix.lower()
            for cat, exts in FILE_TYPES.items():
                if ext in exts:
                    dest = Path(self.folder) / cat
                    dest.mkdir(exist_ok=True)
                    shutil.move(str(file_path), str(dest / file_path.name))
                    print(f"Auto-moved: {file_path.name} to {cat}/")
                    break

observer = Observer()
downloads = str(Path.home() / 'Downloads')
observer.schedule(AutoOrganizer(downloads), downloads, recursive=False)
observer.start()
print("Watching Downloads... Ctrl+C to stop")
Enter fullscreen mode Exit fullscreen mode

Want More Automation Scripts?

I've packaged 25+ production-ready Python automation scripts.

Get the Python Automation Toolkit → — $9 one-time download.

Top comments (0)