mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
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#

  1. os.listdir(path): Lists everything in the folder.
  2. path.join(): Intelligently splices paths, so you don’t have to worry about Windows/Mac slash directions being different.
  3. f"{prefix}_{count+1:03d}{ext}": This is Python’s f-string formatting magic. :03d means “automatically pad with zeros up to 3 digits,” so you get neat sequence numbers like 001, 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-01 folder.
  • Filter Files: Only process .pdf files and delete .txt files.

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/
Author
LeviFREE
Published at
2024-12-12
License
CC BY-NC-SA 4.0

Some information may be outdated

Table of Contents