Batch Renaming Files Script
Problem
You have files like:
IMG_0001.JPGIMG_0001.JPGIMG_0002.JPGIMG_0002.JPG
You want:
photo_0001.jpgphoto_0001.jpgphoto_0002.jpgphoto_0002.jpg
Safe renamer
batch_rename.py
from pathlib import Path
def batch_rename(folder: Path, prefix: str, dry_run: bool = True):
files = sorted([p for p in folder.iterdir() if p.is_file()])
for i, p in enumerate(files, start=1):
new_name = f"{prefix}_{i:04d}{p.suffix.lower()}"
target = p.with_name(new_name)
if dry_run:
print("[DRY RUN]", p.name, "->", target.name)
else:
p.rename(target)
batch_rename(Path("./demo"), prefix="photo", dry_run=True)batch_rename.py
from pathlib import Path
def batch_rename(folder: Path, prefix: str, dry_run: bool = True):
files = sorted([p for p in folder.iterdir() if p.is_file()])
for i, p in enumerate(files, start=1):
new_name = f"{prefix}_{i:04d}{p.suffix.lower()}"
target = p.with_name(new_name)
if dry_run:
print("[DRY RUN]", p.name, "->", target.name)
else:
p.rename(target)
batch_rename(Path("./demo"), prefix="photo", dry_run=True)Tips
- sort filenames for deterministic renames
- use dry runs
- avoid collisions (check if target exists)
๐งช Try It Yourself
Exercise 1 โ List Files with os.listdir
Exercise 2 โ Join Paths with os.path.join
Exercise 3 โ Write and Read a File
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
