Rename Files with Index Prefix in Directory

  • Share this:

Code introduction


This function accepts a directory path and a new file name prefix, renaming all files in the directory. The new file names include the index of the original file name and the prefix.


Technology Stack : Pathlib

Code Type : File operation

Code Difficulty : Intermediate


                
                    
import random
from pathlib import Path, PurePosixPath

def rename_files_in_directory(directory_path, new_name):
    """
    Rename files in a directory based on their index in the list of files.
    """
    # Ensure the directory exists
    if not Path(directory_path).is_dir():
        raise FileNotFoundError(f"The directory {directory_path} does not exist.")
    
    # List all files in the directory
    files = list(Path(directory_path).iterdir())
    
    # Rename files
    for index, file in enumerate(files):
        new_file_name = f"{index}_{new_name}"
        file.rename(file.with_name(new_file_name))                
              
Tags: