Tech With Galvan
Back to Articles
AutomationJun 23, 2029 • 4 min read

How to Automatically Rename and Organise Downloaded Files

Automatically rename and organise downloaded files — Python script that sorts files by type, date, and content. No more messy Downloads folder.

Galvan
Galvan

Founder & Creator

Introduction

Your Downloads folder is a mess: Screenshot 2026-03-08.png, document (1).pdf, IMG_4532.jpg, Untitled spreadsheet (3).xlsx. Finding anything takes 5 minutes.

Automated file organization sorts files by type, date, and content — keeping your Downloads folder clean without manual effort.

The script

import os, shutil, re
from datetime import datetime
from pathlib import Path

DOWNLOADS = Path.home() / "Downloads"
ORGANIZED = Path.home() / "Organized"

# Category rules: (pattern, destination folder)
RULES = [
    (r"\.pdf$", "Documents/PDFs"),
    (r"\.docx?$", "Documents/Word"),
    (r"\.xlsx?$", "Documents/Excel"),
    (r"\.pptx?$", "Documents/PowerPoint"),
    (r"\.csv$", "Documents/CSV"),
    (r"\.(jpg|jpeg|png|gif|webp)$", "Images"),
    (r"\.(mp4|mov|avi|mkv)$", "Videos"),
    (r"\.(mp3|wav|ogg)$", "Audio"),
    (r"\.zip$", "Archives"),
    (r"\.dmg$|\.exe$|\.pkg$", "Installers"),
]

def organize_file(filepath):
    """Organize a single file based on rules."""
    name = filepath.name
    for pattern, dest in RULES:
        if re.search(pattern, name, re.IGNORECASE):
            # Add date subfolder
            mtime = datetime.fromtimestamp(filepath.stat().st_mtime)
            date_folder = mtime.strftime("%Y-%m")
            dest_path = ORGANIZED / dest / date_folder
            dest_path.mkdir(parents=True, exist_ok=True)
            
            # Handle duplicates
            target = dest_path / name
            if target.exists():
                stem = filepath.stem
                suffix = filepath.suffix
                target = dest_path / f"{stem}_{mtime.strftime('%H%M%S')}{suffix}"
            
            shutil.move(str(filepath), str(target))
            print(f"Moved: {name} → {dest}/{date_folder}/")
            return True
    return False

def organize_downloads():
    """Organize all files in the Downloads folder."""
    moved = 0
    skipped = 0
    for f in DOWNLOADS.iterdir():
        if f.is_file() and not f.name.startswith("."):
            if organize_file(f):
                moved += 1
            else:
                skipped += 1
    print(f"\nOrganized: {moved} files moved, {skipped} files skipped")

organize_downloads()

Step 2: Smart renaming

Rename files based on their content or metadata:

def smart_rename(filepath):
    """Rename files with messy names."""
    name = filepath.name
    mtime = datetime.fromtimestamp(filepath.stat().st_mtime)
    
    # Rename screenshots
    if name.lower().startswith("screenshot"):
        new_name = f"screenshot_{mtime.strftime('%Y%m%d_%H%M%S')}{filepath.suffix}"
        filepath.rename(filepath.parent / new_name)
        print(f"Renamed: {name} → {new_name}")
    
    # Rename "Untitled" files
    if name.lower().startswith("untitled"):
        new_name = f"untitled_{mtime.strftime('%Y%m%d_%H%M%S')}{filepath.suffix}"
        filepath.rename(filepath.parent / new_name)
        print(f"Renamed: {name} → {new_name}")
    
    # Rename files with "(1)", "(2)" duplicates
    if re.search(r"\(\d+\)", name):
        base = re.sub(r"\s*\(\d+\)", "", name)
        new_name = f"{Path(base).stem}_copy{Path(base).suffix}"
        filepath.rename(filepath.parent / new_name)
        print(f"Renamed: {name} → {new_name}")

# Apply to all files
for f in DOWNLOADS.iterdir():
    if f.is_file():
        smart_rename(f)

Step 3: Watch folder (auto-organize new downloads)

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

class DownloadHandler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory:
            filepath = Path(event.src_path)
            # Wait for download to complete
            time.sleep(2)
            if filepath.exists():
                organize_file(filepath)
                smart_rename(filepath)

observer = Observer()
observer.schedule(DownloadHandler(), path=str(DOWNLOADS), recursive=False)
observer.start()
print("Watching Downloads folder for new files...")

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()

Now every new download is automatically organized.

Step 4: Schedule cleanup

# Run daily at midnight
0 0 * * * cd /path/to/project && python organize_downloads.py

Custom rules

Add your own rules for specific file types:

RULES = [
    # ... existing rules ...
    (r"invoice", "Documents/Invoices"),       # Any file with "invoice" in name
    (r"receipt", "Documents/Receipts"),       # Any file with "receipt" in name
    (r"resume|cv", "Documents/Resumes"),      # Resumes
    (r"report", "Documents/Reports"),         # Reports
    (r"contract|agreement", "Documents/Contracts"),  # Legal docs
]

Common mistakes

  • Organizing system files — never organize system folders (Applications, Library, etc.)
  • Moving files that are in use — wait for downloads to complete before moving
  • No undo — always test on a copy first. Use shutil.copy2 instead of shutil.move for the first run.
  • Over-organizing — too many folders is as bad as none. Keep it to 8-10 categories.
  • Forgetting to update rules — add new rules as you encounter new file types

Key Concepts

  • File organization = sorting files by type, date, and content
  • Watchdog = Python library for file system monitoring
  • Regex = pattern matching for file names
  • Cron job = scheduled task that runs automatically
  • Naming convention = consistent file naming (date + description + version)

What to Try Next

FAQ

Can I undo the organization?

If you used shutil.move, the files are moved (not copied). To undo, you’d need to move them back manually. For the first run, use shutil.copy2 instead of shutil.move to test.

What about files I’m currently using?

The script skips hidden files and system files. For files in use, the script may fail to move them (Windows locks files). On macOS/Linux, files can usually be moved even when open.

Can I organize cloud folders (Google Drive, Dropbox)?

Yes — if the cloud folder is synced to your local machine (via the desktop app), the script can organize it. Just change DOWNLOADS to the cloud folder path.

How do I handle files with no clear category?

Files that don’t match any rule are skipped. You can add a “Misc” folder for uncategorized files, or review them manually. See Organise Client Projects.