Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

Batch Rename Hundreds of Files in Python

Rename all files with a given extension inside a folder using a sequential counter and a custom prefix.

Easy Python 3.6+ Jun 27, 2026 Automation & scripting 32 views 0 copies

Python code

19 lines
Python 3.6+
import os
from pathlib import Path

def batch_rename_files(directory: str, prefix: str, extension: str = ".txt") -> None:
    """Rename all files with given extension in directory to prefix_{counter}.ext."""
    path = Path(directory)
    if not path.is_dir():
        print(f"Directory '{directory}' does not exist.")
        return

    files = sorted(path.glob(f"*{extension}"))
    for idx, file in enumerate(files, start=1):
        new_name = f"{prefix}_{idx:03d}{extension}"
        new_path = path / new_name
        file.rename(new_path)
        print(f"Renamed: {file.name} -> {new_name}")

if __name__ == "__main__":
    batch_rename_files("sample_files", "document", ".txt")

Output

stdout
Renamed: invoice_1.txt -> document_001.txt
Renamed: invoice_2.txt -> document_002.txt
Renamed: notes.txt -> document_003.txt

How it works

The function uses pathlib.Path.glob to find all files matching the given extension, then enumerate with a start of 1 to produce the sequential counter. Zero-padding with :03d ensures consistent filename lengths for easy sorting. Each file is renamed via Path.rename, which works atomically on a single filesystem. The if __name__ == '__main__' guard prevents the rename from running on import.

Common mistakes

  • Forgetting to list files first before renaming, which can overwrite existing files if the pattern collides
  • Using a counter without zero-padding (e.g., `f'{idx}.'`) which breaks alphabetical sort order after 9 files
  • Renaming files in an unspecified order – always sort with `sorted()` for predictable results

Variations

  1. Use `os.listdir()` and explicit string splitting instead of `pathlib` for Python 2 compatibility
  2. Add a `dry_run=True` parameter to preview renaming without applying changes

Real-world use cases

  • Renaming a batch of invoice PDFs to a standardized naming scheme before uploading to accounting software
  • Reordering photo files from a camera by adding a project prefix and sequence number for archive consistency
  • Normalizing filename formats for data pipeline ingestion where the source system dumps files with random names

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.