A robust Python command-line utility for bulk-renaming and organizing files based on their extensions. Designed with data safety in mind, it includes automated directory creation, comprehensive error handling, and a JSON-backed rollback (undo) feature.
- Command-Line Interface: Fully controlled via terminal arguments using
argparse. - Smart Filtering: Targets specific file extensions while ignoring others.
- Automated Organization: Creates target directories on the fly if they do not exist.
- Fail-Safe Undo Protocol: Safely revert accidental batch renames using a dynamically generated JSON history file.
- Zero Dependencies: Built entirely with Python's standard library (no
pip installrequired).
Navigate to the directory containing your files and run the script from your terminal.
Specify the extensions to target, the destination folder, and the new file prefix.
python main.py --ext .jpg,.png --folder vacation_photos --prefix img_
2. The Undo Feature (Rollback Protocol)
If you accidentally rename the wrong files, or place them in the wrong folder, you can instantly revert the entire batch operation.
Bash
python main.py --undo
How it works: During a rename operation, the script generates a temporary rename_history.json file. This acts as a state map, linking the newly generated file paths back to their original names. When the --undo flag is passed, the script reads this JSON map, safely reverts every file to its original location and name, and cleanly deletes the history file to prevent duplicate rollbacks.
3. Command-Line Help Menu
The tool includes a built-in help menu that details all available flags and default behaviors. Run the following command to view it:
Bash
python main.py --help
Expected Output:
Plaintext
usage: main.py [-h] [-u] [-e EXT] [-f FOLDER] [-p PREFIX]
Bulk rename and organize files, with an undo feature.
options:
-h, --help show this help message and exit
-u, --undo Revert the last batch of renamed files.
-e, --ext EXT File extensions to target (e.g., .jpg,.png)
-f, --folder FOLDER Target folder name (default: 'images')
-p, --prefix PREFIX Prefix for renamed files (default: 'photo-')
🛠️ Technical Architecture
This project was built to demonstrate clean scripting practices, CLI design, and safe file manipulation.
Core Libraries: os, argparse, json
Error Handling: Wrapping file operations in try...except blocks ensures that if a single file throws a PermissionError (locked by another process) or FileNotFoundError, the script logs the error to the console and safely continues processing the rest of the batch without crashing.
State Management (JSON): The decision to use JSON for state mapping allows for persistent memory between terminal sessions. Even if the computer restarts, the --undo command will successfully locate and revert the files.
Data Sanitization: Automatically strips accidental whitespace from user inputs (e.g., handling .jpg, .png vs .jpg,.png) to prevent silent failures during the matching process.