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.
Python code
19 linesimport 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
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
- Use `os.listdir()` and explicit string splitting instead of `pathlib` for Python 2 compatibility
- 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
More from Automation & scripting
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
- Detect and Remove Blurry Images in Python with OpenCV medium
Keep learning
Related tutorials and quizzes for this topic.