DEV Community

Xinglin Ming
Xinglin Ming

Posted on

How to Build a Python File Organizer Script in 5 Minutes

The Problem: Messy Downloads Folder

We all have that one folder where files pile up. PDFs, images, code files, all mixed together.

The Solution

import os
import shutil

EXTENSIONS = {
    'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
    'Documents': ['.pdf', '.docx', '.txt', '.md', '.csv', '.xlsx'],
    'Code': ['.py', '.js', '.html', '.css', '.json'],
    'Archives': ['.zip', '.rar', '.7z', '.tar', '.gz'],
}

def organize(directory):
    for file in os.listdir(directory):
        ext = os.path.splitext(file)[1].lower()
        for folder, exts in EXTENSIONS.items():
            if ext in exts:
                dest = os.path.join(directory, folder)
                os.makedirs(dest, exist_ok=True)
                shutil.move(os.path.join(directory, file), os.path.join(dest, file))
                print(f'Moved: {file} -> {folder}/')
                break

organize('./downloads')
Enter fullscreen mode Exit fullscreen mode

Get More Automation Scripts

I've built 35+ Python scripts. Check them out at my CodeMint Store

Need custom Python work? Email: mactavish.ming@gmail.com

Top comments (0)