Stop 11 · Automation & ScriptingProjects · 1/3

File Organizer Script

Part of the Python Roadmap

In short

Everyone's Downloads folder is a mess of PDFs, screenshots, videos and random zips. This project builds a script that sorts it all into tidy subfolders in one run, safely, with a preview mode and no overwritten files.

A script that scans a messy folder such as Downloads and moves each file into subfolders by type, like Images, PDFs and Videos. It practises pathlib, shutil, argparse and safe handling of name clashes.

The jaadu sits cross-legged on the floor sorting a huge messy heap of papers, photos and film reels into neat labelled baskets around it.

Think of it like this

Sorting the raddi

Before the raddiwala comes, you sort the pile: newspapers here, cardboard there, bottles in a bag, everything else in a box. You look at each item, decide its pile, and move it. The organizer script does exactly that for files, using the file extension to decide each pile.

Watch it happen

Downloads, after one run

Downloads/
Images/
screenshot.png
PDFs/
aadhaar_copy.pdf
aadhaar_copy (1).pdf
Videos/
reel.mp4
Others/
setup.exe

1/5Before: dozens of loose files of every type in one folder.

The big ideas

What you need to know

Map extensions to folders

A dict of category to set of extensions keeps the rules in one place and easy to extend.

Never overwrite

Before moving, check whether the destination exists and add (1), (2) and so on until the name is free.

--dry-run first

A preview mode prints every planned move without touching anything. Run it before the real thing.

Snapshot the list

Read the folder contents into a list before moving files, so the loop never sees the new subfolders mid-run.

See it in code

Walk through the code

python
1import argparse2import shutil3from pathlib import Path4 5CATEGORIES = {6    "Images": {".jpg", ".jpeg", ".png", ".gif", ".webp"},7    "PDFs": {".pdf"},8    "Videos": {".mp4", ".mkv", ".mov"},9    "Documents": {".docx", ".xlsx", ".pptx", ".txt", ".csv"},10}11 12 13def category_for(path: Path) -> str:14    ext = path.suffix.lower()15    for name, extensions in CATEGORIES.items():16        if ext in extensions:17            return name18    return "Others"19 20 21def free_name(folder: Path, filename: str) -> Path:22    dest = folder / filename23    n = 124    while dest.exists():25        dest = folder / f"{Path(filename).stem} ({n}){Path(filename).suffix}"26        n += 127    return dest28 29 30def organise(source: Path, dry_run: bool) -> None:31    for item in list(source.iterdir()):32        if not item.is_file() or item.name.startswith("."):33            continue34        folder = source / category_for(item)35        dest = free_name(folder, item.name)36        print(f"{item.name} -> {folder.name}/{dest.name}")37        if not dry_run:38            folder.mkdir(exist_ok=True)39            shutil.move(item, dest)40 41 42if __name__ == "__main__":43    parser = argparse.ArgumentParser(description="Sort files into folders by type.")44    parser.add_argument("folder", type=Path, help="folder to organise")45    parser.add_argument("--dry-run", action="store_true", help="only print the plan")46    args = parser.parse_args()47    organise(args.folder, args.dry_run)

1/5All the sorting rules in one dict. Sets make each extension lookup fast.

Run python organise.py ~/Downloads --dry-run first. When the plan looks right, run it without the flag.

Save yourself the pain

Common mistakes

Oops

Moving files with shutil.move without checking for existing names.

Do this instead

Generate a free name first. Otherwise a second invoice.pdf can replace the first one.

Oops

Testing for the first time on your real Downloads folder.

Do this instead

Copy a few files into a test folder, or always start with --dry-run.

Oops

Matching extensions case-sensitively.

Do this instead

Phones often save .JPG. Use path.suffix.lower().

Your mission

Make it yours

~60 min

Quick check

Why does the loop use list(source.iterdir()) instead of iterating source.iterdir() directly?

Go deeper

  1. 1Map file extensions to folder names in a dict.
  2. 2Add a --dry-run option that only prints planned moves.
  3. 3Handle files with the same name by adding a number instead of overwriting.

Also part of these roadmaps

More projects at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge