Build a CLI Script to Bulk-Rename or Categorize Files
Objectives
By completing this lab, you will:
-
Build a complete command-line tool using Python (or your preferred language).
-
Apply loops, conditionals, and input validation.
-
Use file operations (rename/move).
-
Handle edge cases, errors, and add logging.
-
Practice real-world problem solving with automation.
Choose a Project Option
You have two options. Pick one, or do both for extra practice:
Option A: Bulk-Rename Files
A script that renames all files in a given directory using a naming scheme (e.g., add prefix, suffix, or sequential numbering).
Option B: Categorize Files
A script that moves files into subfolders based on file types (e.g., .jpg → Images, .pdf → Documents).
Step-by-Step Instructions
Step 1: Setup and Planning
Create a Test Folder:
-
For Rename (Option A):
Create a foldertest_renameand add mixed files (e.g.,file1.txt,image.png,doc.docx). -
For Categorize (Option B):
Create a foldertest_sortand add mixed types (e.g.,photo1.jpg,report.pdf,song.mp3).
Ensure no subfolders exist yet.
Tip: Work on copies of files, not originals, to avoid data loss during testing.
Step 2: Outline the Logic in Pseudocode
Bulk-Rename – Pseudocode
BEGIN
PROMPT for folder path and new filename prefix
SET count = 1
FOR EACH file in folder:
IF file is a directory, CONTINUE
CONSTRUCT new_name = prefix + "_" + count + original extension
RENAME file to new_name
PRINT success message
INCREMENT count
END FOR
PRINT "Renaming complete."
END
Categorize – Pseudocode
BEGIN
PROMPT for folder path
DEFINE categories = {
"Images": [".jpg", ".png", ".gif"],
"Documents": [".pdf", ".docx", ".txt"],
"Audio": [".mp3", ".wav"]
}
FOR EACH file in folder:
IF file is a directory, CONTINUE
SET ext = file extension (lowercased)
FOR EACH category:
IF ext is in category list:
SET dest_folder = category
BREAK
IF no category matched:
SET dest_folder = "Others"
IF dest_folder does not exist:
CREATE it
MOVE file to dest_folder
PRINT move message
END FOR
PRINT "Categorization complete."
END
Step 3: Plan Edge Cases
-
Empty folders: Script should run without errors.
-
Duplicate prefixes (rename): Avoid double-renaming.
-
Filename collisions: Use numbering or unique naming.
-
Categorize: Prevent re-moving already sorted files.
-
Permissions issues: Catch and log exceptions.
-
Skip folders (only operate on files).
Step 4: Implement the Script
Example: Python Script for Bulk Rename (Option A)
import os
# Get user inputs
folder = input("Enter folder path to rename files in: ").strip()
prefix = input("Enter new filename prefix: ").strip()
# Validate input
if not os.path.isdir(folder):
print("Error: Folder not found.")
exit(1)
count = 1
# Loop through files
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
if os.path.isdir(file_path):
continue # Skip folders
name, ext = os.path.splitext(filename)
new_name = f"{prefix}_{count}{ext}"
new_path = os.path.join(folder, new_name)
try:
os.rename(file_path, new_path)
print(f'Renamed "{filename}" to "{new_name}"')
count += 1
except Exception as e:
print(f'ERROR renaming "{filename}": {e}')
print("Renaming complete.")
For File Categorization (Option B), use:
-
os.makedirs(path, exist_ok=True)to create folders if missing. -
shutil.move(src, dst)oros.rename()to move files. -
Loop through categories and match file extensions.
Step 5: Testing
For Rename:
-
Check all files got renamed.
-
Confirm nothing was lost or skipped.
For Categorize:
-
Confirm folders like “Images”, “Documents”, “Audio” were created.
-
Check that files moved correctly.
Example Output – Categorize Script:
Created folder: Images
Moved photo1.jpg -> Images/photo1.jpg
Moved photo2.png -> Images/photo2.png
Created folder: Documents
Moved report.pdf -> Documents/report.pdf
Moved notes.txt -> Documents/notes.txt
Created folder: Audio
Moved song.mp3 -> Audio/song.mp3
File categorization complete.
Test Edge Cases:
-
Empty folder
-
Subfolders present (should skip or handle)
-
Already processed files (optional skip logic)
-
Read-only or restricted files
-
Large number of files
Step 6: Review and Optimize
Optional enhancements:
-
Add a mode selector: rename or categorize
-
Skip already renamed or sorted files
-
Add logging to a file (e.g., log.txt)
-
Add an undo option (if you track original names)
-
Add a dry-run mode to preview actions without making changes
Lab Summary
By the end of this lab, you will have:
Identified a repetitive manual task
Designed logic with pseudocode
Used input handling, loops, and conditionals
Performed file renaming or moving
Tested and handled errors
Built a working CLI script!
