File organization is a practical automation task. This project produces a dry-run plan: it reads filenames, decides which folder each file belongs in, and reports collisions before anything moves.
What you will build#
A program that:
- Takes a list of filenames from input.
- Maps extensions to folder names.
- Groups files by destination.
- Detects duplicate names that would collide in the same folder.
- Prints a dry-run plan.
- Never deletes or moves anything.
Staying read-only is a deliberate safety feature. Automation that renames or deletes files needs confirmation, backups, and careful handling of hidden files and symlinks.
Sample input#
notes.txt photo.jpg script.py data.csv report.pdf archive.zip photo.jpg README
The duplicate photo.jpg is intentional. The plan must warn that two source files would land in the same destination with the same name. A real mover would need to rename one of them.
Mapping extensions#
EXTENSION_FOLDERS = {
".txt": "Documents",
".pdf": "Documents",
".csv": "Data",
".jpg": "Images",
".png": "Images",
".py": "Code",
".zip": "Archives",
}
def destination_for(filename):
suffix = "." + filename.rsplit(".", 1)[1].lower() if "." in filename else ""
return EXTENSION_FOLDERS.get(suffix, "Other")pathlib is cleaner:
from pathlib import PurePath
def destination_for(filename):
suffix = PurePath(filename).suffix.lower()
return EXTENSION_FOLDERS.get(suffix, "Other")PurePath parses a path without touching the filesystem. It handles names such as archive.tar.gz by returning .gz, which is fine for this simple rule. Document that compound extensions are grouped by their final component.
Building the plan#
from collections import defaultdict
def build_plan(filenames):
plan = defaultdict(list)
for filename in filenames:
name = filename.strip()
if not name:
continue
plan[destination_for(name)].append(name)
return dict(plan)defaultdict(list) avoids a membership check before appending. Converting back to a regular dictionary is optional; it makes the return type unsurprising.
Detecting collisions#
def find_collisions(plan):
collisions = []
for folder, files in plan.items():
seen = set()
for filename in files:
base = PurePath(filename).name
if base in seen:
collisions.append((folder, base))
seen.add(base)
return collisionsThis compares base names, not full paths. If you later accept paths with directories, decide explicitly whether a/photo.jpg and b/photo.jpg are the same collision. They are not the same source path, but both would become Images/photo.jpg under a flat destination.
Printing the plan#
def print_plan(plan, collisions):
for folder in sorted(plan):
print(f"{folder}/")
for filename in sorted(plan[folder]):
print(f" {filename}")
print()
if collisions:
print("Collisions detected:")
for folder, name in collisions:
print(f" {folder}/{name} appears more than once")
else:
print("No collisions detected.")Sorting makes the report deterministic. The original input order is not lost if you keep both the list and the plan, but the report is easier to read sorted.
Reading filenames#
raw = input("Filenames separated by commas: ")
filenames = [part.strip() for part in raw.split(",") if part.strip()]Commas work well for a single line. If filenames may contain commas, use one filename per line instead:
filenames = []
while True:
line = input()
if line == "":
break
filenames.append(line.strip())Remember to include the blank terminating line in the supplied Input panel.
Validating names#
Reject entries that are clearly not filenames:
def is_safe_name(filename):
if filename in {".", ".."}:
return False
if "/" in filename or "\\" in filename:
return False
return filename.strip() != ""This project treats names as flat. Allowing separators would complicate the destination rules and create traversal risks. If you extend the tool to real paths, resolve them and verify they remain inside the intended root before moving anything.
Optional Pyodide filesystem experiment#
ILoveCompiler's runtime has an in-memory filesystem. You can create files inside a run and list them, but they disappear when the worker restarts and they are not your computer's real files:
from pathlib import Path
sample = Path("sample.txt")
sample.write_text("hello", encoding="utf-8")
print(sample.read_text(encoding="utf-8"))
sample.unlink()This is useful for learning pathlib, but it is not a reason to call the project a full desktop organizer. Keep the dry-run plan as the core deliverable.
Testing checklist#
- Plan the sample input and verify folder assignments.
- Include an unknown extension and confirm it goes to
Other. - Include
READMEwith no extension. - Include the duplicate photo and confirm the collision warning.
- Include a blank line and confirm it is ignored.
- Test a compound extension such as
archive.tar.gz. - Confirm uppercase extensions group correctly.
Stretch goals#
- Add a
--by-datemode that groups by year and month from a supplied date string. - Generate a shell script of moves for manual review, but do not execute it.
- Detect filenames that differ only by case and report them as a portability risk.
- Read the list from a text file inside Pyodide's virtual filesystem.
- Add tests for
destination_for()andfind_collisions()using plainassertstatements.
