188 words
1 minute
Python Office Automation: Write a Batch Rename Script in 5 Minutes
Have you ever encountered this situation:
Your boss sends you 500 event photos, and all the filenames are gibberish like IMG_20260131_123456.jpg, asking you to rename them all to Event_001.jpg, Event_002.jpg…?
Rename manually? You’ll be doing that until next year. With Python, it only takes the time it takes to drink a glass of water.
1. Preparation
Ensure Python is installed on your computer. We only need the built-in os library; no third-party packages are required.
2. Core Code
Create a new file rename.py:
import os
def batch_rename(path, prefix): # 1. Ensure the path exists if not os.path.exists(path): print(f"Path {path} does not exist!") return
# 2. Get all files in the directory files = os.listdir(path) # Sort by original filename to prevent mixed order files.sort()
count = 0 for filename in files: # Skip hidden files (like .DS_Store) and the script itself if filename.startswith('.') or filename == 'rename.py': continue
# 3. Construct the new filename # Get file extension (e.g., .jpg) ext = os.path.splitext(filename)[1]
# Format numbers, e.g., 001, 002 new_name = f"{prefix}_{count+1:03d}{ext}"
old_file = os.path.join(path, filename) new_file = os.path.join(path, new_name)
# 4. Execute renaming try: os.rename(old_file, new_file) print(f"✅ {filename} -> {new_name}") count += 1 except Exception as e: print(f"❌ Failed to rename {filename}: {e}")
print(f"\n🎉 Done! Processed {count} files in total.")
if __name__ == "__main__": # Modify your folder path and desired prefix here target_path = "./photos" new_prefix = "Event"
batch_rename(target_path, new_prefix)3. Code Breakdown
os.listdir(path): Lists everything in the folder.path.join(): Intelligently splices paths, so you don’t have to worry about Windows/Mac slash directions being different.f"{prefix}_{count+1:03d}{ext}": This is Python’s f-string formatting magic.:03dmeans “automatically pad with zeros up to 3 digits,” so you get neat sequence numbers like001,009,010.
4. Expansion Ideas
Once you grasp this logic, you can do much more:
- Archive by Date: Read the file’s creation time and automatically move it to a
2026-01folder. - Filter Files: Only process
.pdffiles and delete.txtfiles.
Learning the programming mindset, even just through small scripts like this, can vastly improve your workplace happiness.
Share
If this article helped you, please share it with others!
Python Office Automation: Write a Batch Rename Script in 5 Minutes
https://blog.levifree.com/posts/python-rename-script/ Some information may be outdated
The Art of Refactoring: How to Write TypeScript Code That Won't Make Your Colleagues Curse
Git Conflict Resolution Playbook: A Standard Process from Location to Convergence
Related Posts Smart
1
Git in Practice: Three Methods to Keep Your Fork Repo Synced with Upstream
DevOps From clicking buttons to automated scripts: master Git Upstream synchronization techniques comprehensively.
2
Deploying Nginx Proxy Manager with Docker: Reverse Proxy Made Easy for Beginners
DevOps Say goodbye to tedious Nginx configuration files and easily manage SSL certificates and domain forwarding using a visual dashboard.
3
Linux Server Security Baseline in Practice: 12 Must-Do Hardening Steps Before Going Live
Security From accounts, SSH, and firewalls to log auditing, providing solo webmasters an actionable go-live checklist.
4
AMH Panel Website Building Practice: Deploying a High-Performance WordPress Blog from Scratch
DevOps A comprehensive guide on Linux environment configuration and AMH panel usage based on Azure B1s / VPS.
5
Next.js App Router Getting Started Guide: From Routing to Server-Side Rendering
Web Forget getStaticProps? A minimalist explanation of Next.js 14+ core concepts.
Random Posts Random
1
Git Conflict Resolution Playbook: A Standard Process from Location to Convergence
DevOps 2024-12-03
2
Static Blog Content Cluster Strategy: Upgrading Scattered Tech Articles into Systematic Topics
SEO 2025-10-14
3
SSH Key Security Guide: Five Steps to Prevent Server Hacks
Security 2025-11-05
4
Linux Server Security Baseline in Practice: 12 Must-Do Hardening Steps Before Going Live
Security 2024-06-18
5
Nginx 502/504 Troubleshooting Guide: Locating and Fixing Common Reverse Proxy Failures
DevOps 2025-06-28





