AI & Python Developer

All posts

Batch Renaming Files with Python’s pathlib and glob for Quick Data Prep

2 min read

  • python
  • automation
  • data-preprocessing
  • file-management

When you start a new ML project, the first thing you often see is a folder full of images, CSVs, or logs with inconsistent names.
Manually renaming them is tedious and error‑prone. In this post I’ll show a clean, Python‑only method to batch rename files using pathlib and glob. The code works on Windows, macOS, and Linux without any extra dependencies.

Why pathlib + glob?

  • pathlib gives an object‑oriented interface to file paths. No more string concatenation.
  • glob (available through Path.glob) lets you select files with Unix‑style patterns (*.jpg, data_*.csv).
  • Both are part of the Python standard library, so you don’t need to install anything.

Step‑by‑step guide

1. Define the folder and pattern

from pathlib import Path

# Folder containing the files
base_dir = Path("data/raw_images")

# Select all JPG files
files = list(base_dir.glob("*.JPG"))   # case‑sensitive on Linux

Explanation: Path("data/raw_images") creates a Path object. glob("*.JPG") returns an iterator of matching files.

2. Decide on the new naming scheme

For this example we’ll rename files to img_001.jpg, img_002.jpg, … preserving the original extension.

new_prefix = "img_"
pad_width = 3  # 001, 002, …

3. Loop and rename

for i, old_path in enumerate(sorted(files), start=1):
    new_name = f"{new_prefix}{i:0{pad_width}d}{old_path.suffix.lower()}"
    new_path = old_path.with_name(new_name)
    old_path.rename(new_path)

Explanation:

  • sorted(files) ensures a deterministic order (alphabetical).
  • old_path.suffix.lower() keeps the extension in lower case.
  • with_name() builds a new Path in the same directory.
  • rename() performs the move/rename operation.

4. Add a safety check (optional)

It’s easy to accidentally overwrite files. A quick guard can prevent that:

if new_path.exists():
    raise FileExistsError(f"{new_path} already exists!")

Insert this before old_path.rename(new_path) if you want the script to stop on a conflict.

5. Run the script

Save the code as rename_batch.py and execute:

python rename_batch.py

You should see the files in data/raw_images renamed to img_001.jpg, img_002.jpg, etc.

Common variations

Goal Code tweak
Rename only files that contain a keyword (e.g., “cat”) base_dir.glob("*cat*.JPG")
Change extension from .png to .jpg new_name = f"{new_prefix}{i:0{pad_width}d}.jpg"
Add a timestamp prefix from datetime import datetime<br>ts = datetime.now().strftime("%Y%m%d_")<br>new_name = f"{ts}{new_prefix}{i:0{pad_width}d}{old_path.suffix}"
Move renamed files to a new folder target_dir = Path("data/processed")<br>new_path = target_dir / new_name

All these adjustments stay within the same concise pattern.

Tips for beginners

  • Test on a copy – before running on the real dataset, duplicate the folder and try the script there.
  • Use print statements – add print(old_path, "→", new_path) inside the loop to see what will happen.
  • Version control – if your data lives in a Git repo, commit before renaming; you can always revert.

When to use a dedicated tool

For extremely large collections (hundreds of thousands of files) or complex metadata‑driven renames, a specialized tool like exiftool or a database‑backed approach may be faster. The Python method shines for small‑to‑medium batches and when you want the logic to be part of a larger pipeline.

Key takeaways

  • pathlib + glob gives a clean, cross‑platform way to select and rename files.
  • Build the new name with f‑strings, preserve the extension with suffix, and rename with Path.rename.
  • Add optional safety checks and test on a copy to avoid accidental data loss.