Python Central HubSign in

Automation and Scripting / Phase 1: OS & File System Automation

Batch Renaming Files Script

Rename many files safely with a dry-run option.

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.

Problem

You have files like:

  • IMG_0001.JPG
  • IMG_0002.JPG

You want:

  • photo_0001.jpg
  • photo_0002.jpg

Safe renamer

Python
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

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 โ€“ Join Paths with os.path.join

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 โ€“ Write and Read a File

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did