Skip to content

Batch Renaming Files Script

diagram batch renaming, and the two ways it destroys data mermaid
Renaming in a loop has two failure modes that a first version almost always has. A target that already exists is either an error or a silent overwrite depending on the platform and the call. And a sequence like 1->2, 2->3 can consume its own inputs if the order is wrong. Both are avoided by planning the whole mapping first.

You have files like:

  • IMG_0001.JPG
  • IMG_0002.JPG

You want:

  • photo_0001.jpg
  • photo_0002.jpg
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)
  • sort filenames for deterministic renames
  • use dry runs
  • avoid collisions (check if target exists)

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading