Batch Renaming Files Script
flowchart TD
A["collect the files"] --> B["build the full old -> new mapping"]
B --> C{"any duplicate targets?"}
C -->|yes| D["stop -- two files want the same name"]
C -->|no| E{"does any target already exist?"}
E -->|yes| F["stop, or rename via a temporary name"]
E -->|no| G{"does any target collide with a source?"}
G -->|yes| H["two-pass: everything to temp names, then to finals"]
G -->|no| I["print the plan"]
H --> I
I --> J{"--apply given?"}
J -->|no| K["done -- nothing changed"]
J -->|yes| L["os.replace for deliberate overwrite, os.rename otherwise"]
Problem
Section titled “Problem”You have files like:
IMG_0001.JPGIMG_0002.JPG
You want:
photo_0001.jpgphoto_0002.jpg
Safe renamer
Section titled “Safe renamer”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)
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading