Automate everyday tasks with Python · Lesson 14 of 14
Project: tidy my Downloads folder
Build a complete automation script: sort a messy Downloads folder into sub-folders by file type, avoid overwriting, and write a CSV report.
Time to put the course together. The Downloads folder of most computers is a mess of photos, PDFs, installers and music. In this project you build a script that sorts it into sub-folders by type, never overwrites a file, offers a dry run and writes a CSV report of everything it did. The plan, step by step:
- 1. Decide a folder for every file from its extension (Paths with pathlib).
- 2. List the files in a fixed order and plan each move (Listing and finding files).
- 3. Move them, picking a free name when one is taken (Rename, copy, move and organise files).
- 4. Save a report as CSV (CSV files with the csv module).
- 5. Add arguments and run it on your real folder (Command-line scripts).
Step 1: a folder for every file
A dictionary maps each folder to the set of extensions that belong in it. The extension is lower-cased first, so Holiday.JPG and beach.jpg end up together. Anything unknown goes into other. Test the function on a few names before going further.
import csv
import shutil
from pathlib import Path
CATEGORIES = {
"images": {".jpg", ".jpeg", ".png", ".gif"},
"documents": {".pdf", ".docx", ".xlsx", ".csv", ".txt"},
"music": {".mp3", ".wav"},
}
def category_for(path):
ext = path.suffix.lower()
for folder, extensions in CATEGORIES.items():
if ext in extensions:
return folder
return "other"
def free_name(target):
n = 1
candidate = target
while candidate.exists():
candidate = target.with_stem(f"{target.stem} ({n})")
n += 1
return candidate
def should_skip(path):
# hidden and system files (desktop.ini on Windows) and unfinished downloads
return (path.name.startswith(".") or path.name.lower() == "desktop.ini"
or path.suffix.lower() in {".crdownload", ".part"})
def tidy(folder, dry_run=True):
rows = []
files = sorted((p for p in folder.iterdir() if p.is_file() and not should_skip(p)),
key=lambda p: p.name)
for p in files:
category = category_for(p)
target = free_name(folder / category / p.name)
status = "would move" if dry_run else "moved"
if not dry_run:
target.parent.mkdir(exist_ok=True)
shutil.move(p, target)
rows.append({"file": p.name, "folder": category, "new_name": target.name, "status": status})
return rows
def write_report(rows, path):
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["file", "folder", "new_name", "status"])
writer.writeheader()
writer.writerows(rows)
for name in ["Holiday.JPG", "cv.docx", "podcast.mp3", "setup.exe", "notes"]:
print(f"{name:12} -> {category_for(Path(name))}")Holiday.JPG -> images cv.docx -> documents podcast.mp3 -> music setup.exe -> other notes -> other
Step 2: a dry run
The example folder below is a typical mess: nine loose files, one without an extension, and an images folder that already contains a photo.jpg. tidy() lists the files in name order, picks a folder and a free name for each, and only moves anything when dry_run is False. should_skip() leaves hidden and system files alone (Windows keeps a hidden desktop.ini in Downloads that gives the folder its name and icon), as well as downloads that are still in progress. First, the dry run:
import csv
import shutil
from pathlib import Path
CATEGORIES = {
"images": {".jpg", ".jpeg", ".png", ".gif"},
"documents": {".pdf", ".docx", ".xlsx", ".csv", ".txt"},
"music": {".mp3", ".wav"},
}
def category_for(path):
ext = path.suffix.lower()
for folder, extensions in CATEGORIES.items():
if ext in extensions:
return folder
return "other"
def free_name(target):
n = 1
candidate = target
while candidate.exists():
candidate = target.with_stem(f"{target.stem} ({n})")
n += 1
return candidate
def should_skip(path):
# hidden and system files (desktop.ini on Windows) and unfinished downloads
return (path.name.startswith(".") or path.name.lower() == "desktop.ini"
or path.suffix.lower() in {".crdownload", ".part"})
def tidy(folder, dry_run=True):
rows = []
files = sorted((p for p in folder.iterdir() if p.is_file() and not should_skip(p)),
key=lambda p: p.name)
for p in files:
category = category_for(p)
target = free_name(folder / category / p.name)
status = "would move" if dry_run else "moved"
if not dry_run:
target.parent.mkdir(exist_ok=True)
shutil.move(p, target)
rows.append({"file": p.name, "folder": category, "new_name": target.name, "status": status})
return rows
def write_report(rows, path):
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["file", "folder", "new_name", "status"])
writer.writeheader()
writer.writerows(rows)
downloads = Path("downloads")
for row in tidy(downloads, dry_run=True):
print(f"{row['status']}: {row['file']} -> {row['folder']}/{row['new_name']}")would move: Holiday.JPG -> images/Holiday.JPG would move: cv.docx -> documents/cv.docx would move: data.csv -> documents/data.csv would move: invoice_2026-03.pdf -> documents/invoice_2026-03.pdf would move: notes -> other/notes would move: photo.jpg -> images/photo (1).jpg would move: podcast.mp3 -> music/podcast.mp3 would move: scan_0012.png -> images/scan_0012.png would move: setup.exe -> other/setup.exe
Step 3: the real run and the report
Look at photo.jpg in the dry run: there is already one in images, so the script plans photo (1).jpg instead of overwriting it, and the images folder itself is skipped because is_file() is false for it. When the plan looks right, run it for real, write the report and look at the result. The report goes next to the folder, not inside it, so the next run does not sort the report too. Running the script a second time is a good test: there should be nothing left to move.
import csv
import shutil
from pathlib import Path
CATEGORIES = {
"images": {".jpg", ".jpeg", ".png", ".gif"},
"documents": {".pdf", ".docx", ".xlsx", ".csv", ".txt"},
"music": {".mp3", ".wav"},
}
def category_for(path):
ext = path.suffix.lower()
for folder, extensions in CATEGORIES.items():
if ext in extensions:
return folder
return "other"
def free_name(target):
n = 1
candidate = target
while candidate.exists():
candidate = target.with_stem(f"{target.stem} ({n})")
n += 1
return candidate
def should_skip(path):
# hidden and system files (desktop.ini on Windows) and unfinished downloads
return (path.name.startswith(".") or path.name.lower() == "desktop.ini"
or path.suffix.lower() in {".crdownload", ".part"})
def tidy(folder, dry_run=True):
rows = []
files = sorted((p for p in folder.iterdir() if p.is_file() and not should_skip(p)),
key=lambda p: p.name)
for p in files:
category = category_for(p)
target = free_name(folder / category / p.name)
status = "would move" if dry_run else "moved"
if not dry_run:
target.parent.mkdir(exist_ok=True)
shutil.move(p, target)
rows.append({"file": p.name, "folder": category, "new_name": target.name, "status": status})
return rows
def write_report(rows, path):
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["file", "folder", "new_name", "status"])
writer.writeheader()
writer.writerows(rows)
downloads = Path("downloads")
rows = tidy(downloads, dry_run=False)
write_report(rows, "tidy_report.csv")
print(len(rows), "files moved")
with open("tidy_report.csv", encoding="utf-8") as f:
print(f.read().strip())
print("Folders now:")
for p in sorted(downloads.rglob("*"), key=lambda p: p.as_posix()):
if p.is_file():
print(" ", p.relative_to(downloads).as_posix())
print("Second run:", len(tidy(downloads, dry_run=False)), "files moved")9 files moved file,folder,new_name,status Holiday.JPG,images,Holiday.JPG,moved cv.docx,documents,cv.docx,moved data.csv,documents,data.csv,moved invoice_2026-03.pdf,documents,invoice_2026-03.pdf,moved notes,other,notes,moved photo.jpg,images,photo (1).jpg,moved podcast.mp3,music,podcast.mp3,moved scan_0012.png,images,scan_0012.png,moved setup.exe,other,setup.exe,moved Folders now: documents/cv.docx documents/data.csv documents/invoice_2026-03.pdf images/Holiday.JPG images/photo (1).jpg images/photo.jpg images/scan_0012.png music/podcast.mp3 other/notes other/setup.exe Second run: 0 files moved
Step 4: on your own computer
The last step wraps everything in a command-line interface. Save the functions above together with the code below as tidy.py. Start with python tidy.py (a dry run of your Downloads folder), read the plan, then run python tidy.py --go to really move the files. Add it to Task Scheduler or cron, as in Command-line scripts, to tidy every week.
import argparse
import sys
from pathlib import Path
# ... CATEGORIES, category_for, free_name, should_skip, tidy and write_report from above ...
def main(argv):
parser = argparse.ArgumentParser(prog="tidy", description="Sort a folder into sub-folders by file type.")
parser.add_argument("folder", nargs="?", default=str(Path.home() / "Downloads"))
parser.add_argument("--go", action="store_true", help="really move the files (default: dry run)")
args = parser.parse_args(argv)
folder = Path(args.folder)
if not folder.is_dir():
print(f"{folder} is not a folder")
return 1
rows = tidy(folder, dry_run=not args.go)
for row in rows:
print(f"{row['status']}: {row['file']} -> {row['folder']}/{row['new_name']}")
write_report(rows, folder.parent / "tidy_report.csv")
print(len(rows), "files", "moved" if args.go else "planned (dry run, add --go to move)")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))Runs on your own computer. Without --go no file is moved; only the plan is written to tidy_report.csv next to the folder (it replaces the previous report).
✎ Exercise
A colleague sends you a report from the script, tidy_report.csv. Read it with csv.DictReader and print how many files went into each folder, folders in alphabetical order, then the total. Each line shows the name left-aligned in 10 characters, a space and the number; the last line uses the name total.
Hint: Count with a dictionary: counts[row["folder"]] = counts.get(row["folder"], 0) + 1.
import csv
# your code here
Expected output:
documents 2 images 2 music 1 other 2 total 7
Show a solution
import csv
counts = {}
with open("tidy_report.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
counts[row["folder"]] = counts.get(row["folder"], 0) + 1
for folder in sorted(counts):
print(f"{folder:10} {counts[folder]}")
print(f"{'total':10} {sum(counts.values())}")documents 2 images 2 music 1 other 2 total 7
✎ Exercise
Extend the sorting rules: add an archives folder for .zip, .7z and .tar files and an installers folder for .exe and .msi. For each name in names, print the name left-aligned in 11 characters, then -> and the folder chosen for it.
Hint: Add two entries to the dictionary and reuse category_for() from the lesson; lower() the suffix so .ZIP matches .zip.
from pathlib import Path
CATEGORIES = {
"images": {".jpg", ".jpeg", ".png", ".gif"},
"documents": {".pdf", ".docx", ".xlsx", ".csv", ".txt"},
}
names = ["backup.ZIP", "setup.exe", "map.png", "fonts.7z", "readme"]
# your code here
Expected output:
backup.ZIP -> archives setup.exe -> installers map.png -> images fonts.7z -> archives readme -> other
Show a solution
from pathlib import Path
CATEGORIES = {
"images": {".jpg", ".jpeg", ".png", ".gif"},
"documents": {".pdf", ".docx", ".xlsx", ".csv", ".txt"},
"archives": {".zip", ".7z", ".tar"},
"installers": {".exe", ".msi"},
}
names = ["backup.ZIP", "setup.exe", "map.png", "fonts.7z", "readme"]
def category_for(path):
ext = path.suffix.lower()
for folder, extensions in CATEGORIES.items():
if ext in extensions:
return folder
return "other"
for name in names:
print(f"{name:11} -> {category_for(Path(name))}")backup.ZIP -> archives setup.exe -> installers map.png -> images fonts.7z -> archives readme -> other
Check yourself
1. Why does the script lower-case the extension before looking it up?
Extensions are typed in any case; comparing suffix.lower() treats them alike on every system.
2. What happens to photo.jpg when images/photo.jpg already exists?
free_name() adds (1), (2)… until the name is free.
3. Why is the report written outside the folder being tidied?
A report inside the folder would be picked up and moved into documents next time.