Script: Rename all files of a particular file extension in a Windows folder

This Python script allows to rename all of the files of a particular file extension in a folder.

Very useful when you download multiple files off the web for a similar topic, but all have different names.

In this short demo it can be appreciated how all, and only, the images with a “.jpg” extension are renamed in a format that starts with “Dog_” followed by a number sequence of 3 digits.

Below  is an images of the folder with all the images before running the script.

Followed by an image after running the script.

The images with file extension other than “.jpg” were left untouched.

 

This script allows to provide the extension, a name prefix, the amount of digits in the sequence used for naming and a starting number.

This was the input entered to obtain the results from the demo.

When this script used in combination with the script that allows to change the file extension, which can be found in the projects section, it can be very powerful.


#Rename by extension

import os

def rename_files_with_extension(folder_path, extension, prefix, digits, startingnumber):
    x=int(startingnumber)

    for filename in os.listdir(folder_path):
        if filename.endswith(extension):
            file_path = os.path.join(folder_path, filename)
            new_name = os.path.join(folder_path, prefix+str(x).zfill(digits)+"."+extension)
            os.rename(file_path, new_name)
            x=x+1
    print("Renaming Completed")
    
# Specify the  file extension
extension = input("Enter file extension (do not add the \".\"): ")

# Specify the folder path where the files are located
folder_path =  input("Enter the full folder path: ")

# Specify the  prefix
prefix = input("Enter the name of the files (prefix): ")

# Specify the  amount of digits
digits = int(input("Enter amount of digits (for \"000\" enter 3): "))

# Specify the  starting number
startingnumber = input("Enter starting number: ")

# Call the function to rename the files
rename_files_with_extension(folder_path, extension, prefix, digits, startingnumber)

Note: None of the inputs are validated, therefore it is not protected against invalid input.