CASE STUDY 03 · PYTHON

Advanced pathlib + shutil + Safety

Safe File Organizer

Inspect a real directory, classify top-level files, preview every move, avoid overwriting duplicate names and apply the plan only after explicit confirmation.

01 · PROBLEM DEFINITION

Automation must be safer than manual movement

A Downloads folder may contain images, documents, spreadsheets, archives, code and unknown files. The organizer groups top-level files into named subfolders based on lowercase extensions. Because movement changes real filesystem state, correctness includes avoiding overwrites, showing a preview and allowing cancellation with zero changes.

Discover

Inspect only direct child files of the selected folder.

Plan

Resolve category and a non-conflicting destination.

Apply

Create required folders and move after confirmation.

First-use rule: Test on a temporary folder containing copies—not valuable originals. Filesystem permissions, locks and cross-device moves vary by environment.
02 · SAFETY RULES & SCOPE

Define exclusions before scanning

  1. The selected path must exist and be a directory.
  2. Only top-level regular files are candidates; subdirectories are not traversed.
  3. The running organizer script excludes itself.
  4. Extension comparison is case-insensitive.
  5. Unknown or extensionless files go to Other.
  6. An existing destination is never overwritten.
  7. No movement begins unless the user types exactly MOVE.

The narrow, non-recursive scope prevents accidentally reorganizing an entire nested project. Recursion can be an extension only after symlink handling, protected folders and rollback are designed.

03 · CLASSIFICATION MODEL

A mapping keeps policy separate from movement

CATEGORIES = {
  "Images": {".jpg", ".png", ...},
  "Documents": {".pdf", ".docx", ...},
  "Code": {".py", ".c", ".html", ...}
}

category_for lowercases Path.suffix and searches the mapping. The classification rule is data, so adding an extension does not change the planning algorithm.

Important ambiguity

archive.tar.gz has .gz as its final suffix and is classified as an archive. A richer policy might inspect suffixes. A file extension is only a naming convention; it does not verify actual content. Security-sensitive systems need content inspection.

04 · TWO-PHASE WORKFLOW

Separate decision from mutation

Resolve folder
List candidate files
Build source→destination plan
Print preview
Confirm MOVE
Apply moves

A dry preview lets the user detect a wrong directory or classification before anything changes. The plan is also testable without modifying files: provide a temporary directory, call build_plan and inspect its tuples.

The program sorts source names case-insensitively so preview order is deterministic. Determinism makes screenshots, tests and troubleshooting easier.

05 · COLLISION-SAFE DESTINATIONS

Never trade organization for data loss

If Images/photo.jpg already exists, moving another photo.jpg to that exact path could overwrite or fail depending on platform. The organizer tests the candidate and generates photo_1.jpg, photo_2.jpg, and so on until an unused name is found.

candidate = category / original_name
while candidate exists:
    candidate = category / f"{stem}_{counter}{suffix}"

This preserves both files, though it does not determine whether they contain duplicate bytes. Hash-based duplicate detection is a separate policy that should offer review rather than silently delete.

06 · COMPLETE IMPLEMENTATION

Runnable Python program using real files

programs/file-organizer.py
Loading source…
Local execution required: Copy the program into a safe test folder and run it locally. An online compiler cannot reliably access or preserve your computer’s directory.
07 · INTERACTIVE PROGRAM TRACE

Trace a five-file test folder

  1. Start with copied test files.
  2. Validate target.
  3. Apply exclusions.
  4. Classify case-insensitively.
  5. Finish classification.
  6. Resolve collision before moving.
  7. Display preview.
  8. Confirm mutation.
  9. Apply and report.
Current state

Press Next to begin.

08 · TEMPORARY-DIRECTORY TESTS

Verify without risking personal data

Cancellation
Build a plan, enter anything except MOVE and assert the complete directory tree is unchanged.
Case-insensitive extension
PHOTO.JPG and icon.PnG must both move under Images.
Unknown and extensionless
sample.xyz and README must move under Other.
Name collision
Pre-create Images/photo.jpg; the incoming photo.jpg must become photo_1.jpg without modifying the original.
Subdirectory exclusion
A nested project directory and its contents must remain untouched.
Partial OS failure
Simulate one failed move; the program reports it and accurately counts successful moves.
09 · COMPLEXITY & FAILURE MODEL

Directory scanning is linear; I/O dominates

PhaseTimeMemory
List/sort n entriesO(n log n)O(n)
ClassificationO(nc)O(n)
Apply movesO(n) operationsO(1) extra

c is the small number of categories. A sequence of filesystem moves is not atomic: power loss may leave a partially organized folder. A stronger version records a journal before each move and supports rollback. It must also define behavior for symbolic links and cross-filesystem copies.

10 · PRACTICE & EXTENSIONS

Check safe automation principles

Why build a complete plan before moving?

What should happen when a destination name exists?

Extensions

  1. Create a move journal and Undo Last Run.
  2. Add modification-year subfolders after category.
  3. Detect byte-identical files using hashes but require review before deletion.
  4. Add configurable rules from JSON.
  5. Design safe recursion with symlink-cycle protection.
11 · INTERVIEW PREPARATION

Explain filesystem safety

Why pathlib?

It provides readable, cross-platform path objects and avoids fragile manual path-string concatenation.

Why not overwrite?

Matching filenames do not prove matching content. Overwrite could irreversibly destroy the earlier file.

Is preview enough for atomicity?

No. It prevents unintended starts, but failures during application can still leave partial results. A journal/rollback or transactional storage is needed.

Why skip directories?

Recursive reorganization expands risk dramatically and requires explicit rules for nested structure, symlinks and protected folders.

12 · KEY TAKEAWAY

Good automation makes consequences visible first

The Python APIs are straightforward; the engineering value lies in constrained scope, deterministic planning, explicit confirmation, collision protection, precise error reporting and temporary-directory tests.