Rename Files in Folder with Numeric Prefix in Python

Renames all files in a folder by adding a sequential numeric prefix (e.g., 01_, 02_) to each filename using pathlib.

Easy Python 3.4+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

23 lines
Python 3.4+
from pathlib import Path

def rename_with_numeric_prefix(folder_path):
    folder = Path(folder_path)
    for index, file_path in enumerate(folder.iterdir(), start=1):
        if file_path.is_file():
            new_name = f"{index:02d}_{file_path.name}"
            new_path = file_path.with_name(new_name)
            file_path.rename(new_path)
            print(f"Renamed {file_path.name} -> {new_name}")

if __name__ == "__main__":
    # Example usage: create sample files and rename them
    import tempfile
    import os
    
    with tempfile.TemporaryDirectory() as temp_dir:
        for name in ["apple.txt", "banana.txt", "cherry.txt"]:
            Path(temp_dir, name).write_text("sample")
        
        print(f"Before: {sorted(os.listdir(temp_dir))}")
        rename_with_numeric_prefix(temp_dir)
        print(f"After: {sorted(os.listdir(temp_dir))}")

Output

stdout
Before: ['apple.txt', 'banana.txt', 'cherry.txt']
Renamed apple.txt -> 01_apple.txt
Renamed banana.txt -> 02_banana.txt
Renamed cherry.txt -> 03_cherry.txt
After: ['01_apple.txt', '02_banana.txt', '03_cherry.txt']

How it works

Path.iterdir() yields all entries in the folder, and the is_file() check filters out subdirectories. The enumerate function with start=1 provides a 1-based index, and the f-string {index:02d} formats numbers with at least two digits (e.g., 1 becomes 01). file_path.with_name(new_name) builds a new path with the same parent directory, preserving the original location. Finally, Path.rename() renames the file, and printing confirms each action.

Common mistakes

  • Forgetting to check `is_file()`, which would try to rename directories and cause errors.
  • Using `os.listdir()` without sorting, resulting in inconsistent numbering when order matters.
  • Not padding numbers (e.g., using `{index}` instead of `{index:02d}`), giving a non-uniform filename pattern.

Variations

  1. Use `pathlib.Path.glob('*')` to select only files (not directories) by pattern.
  2. Specify a custom prefix like `f'{index:03d}_backup_'` for more complex naming.

Real-world use cases

  • Quickly organizing downloaded files (e.g., photos or reports) in a folder sequentially.
  • Preparing batches of files for processing pipelines that require ordered inputs.
  • Adding a numeric index to configuration files when sorting, e.g., 01_settings.yaml, 02_settings.yaml.

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.