How to Organize Files with Python
Downloads folders, site photo folders and shared drives all end up the same way: hundreds of files, no structure. A short Python script can sort them by type or by date in seconds — and the safe version below always shows you what it will do before it moves anything.
Step 1: The golden rule — dry run first, backup always
Never run a file-moving script on originals without a backup. Copy the folder first, or point the script at a test copy. The script below has a DRY_RUN switch: with it on, it only prints planned moves. Run it, read the plan, and only then turn the switch off.
Step 2: The sorting script
from pathlib import Path
import shutil
SOURCE = Path("Downloads") # change to your folder (use a COPY first)
DEST = Path("Downloads_organized")
DRY_RUN = True # True = only print the plan; False = actually move
GROUPS = {
"Images": {".jpg", ".jpeg", ".png", ".gif", ".webp"},
"Documents": {".pdf", ".docx", ".xlsx", ".txt", ".csv"},
"Videos": {".mp4", ".mov", ".mkv"},
"Archives": {".zip", ".rar", ".7z"},
}
def group_for(suffix):
for name, exts in GROUPS.items():
if suffix.lower() in exts:
return name
return "Other"
for f in SOURCE.iterdir():
if not f.is_file():
continue
target = DEST / group_for(f.suffix) / f.name
if DRY_RUN:
print(f"Would move: {f.name} -> {target}")
else:
target.parent.mkdir(parents=True, exist_ok=True)
if target.exists(): # never silently overwrite
print(f"SKIP (exists): {target}")
continue
shutil.move(str(f), str(target))
print("Dry run done." if DRY_RUN else "Organizing done.")Step 3: Variations worth knowing
Sort by date instead: use datetime.fromtimestamp(f.stat().st_mtime) and group into 2026-10 style folders. Rename in bulk: build the new name from the old one plus a counter, and again print first. Watch a folder continuously: the watchdog library (install with pip) triggers the same sorting logic whenever a new file appears — useful for a shared uploads folder.
Common mistakes
Running on originals with no backup; overwriting same-named files (this script refuses to); sorting a folder the operating system or another program is actively writing to; and sorting by extension alone when extensions lie — for photos, the file's date metadata is more reliable than its name.
Frequently asked questions
Is it safe to run on my real Downloads folder?
Only after a backup and a dry run. The script above refuses to overwrite existing files, but a backup is still the rule — scripts act on hundreds of files in a second, and undoing that by hand is painful.
Can it sort by date instead of type?
Yes: replace the group logic with the file's modification date formatted as year-month. The rest of the script — dry run, no-overwrite, move — stays the same.
How do I make it run automatically?
Schedule it with Task Scheduler or cron, pointed at a specific folder, with logging enabled. Start with a weekly schedule and review the log before making it daily.