Batch File Renaming with Python

Batch File Renaming with Python

Illustration of batch file renaming automation using Python scripting.

Renaming multiple files manually can be time-consuming and prone to errors. A Python script allows you to automate file renaming efficiently, whether you’re organizing photos, documents, or data files.

In this guide, you’ll learn:

  • How to rename files in bulk using Python.
  • Quick and easy ways to generate the name list of your files to be renamed.
  • A no-code file renaming alternative using Windows File Explorer.

The following Python script renames files in bulk based on mapping stored in an Excel spreadsheet.


import os
import pandas as pd

# ------------------------------
# STEP 1: Load the Excel File
# ------------------------------
excel_file = "file-renaming.xlsx"  # Ensure this file is in the same directory as this python script.

# Prompt user to enter the directory where files to be renamed are stored
directory = input("Enter the directory where the files to be renamed are stored: ")

# ------------------------------
# STEP 2: Read the Excel File
# ------------------------------
try:
    df = pd.read_excel(excel_file)  # Load the spreadsheet
except Exception as e:
    print(f"Error reading Excel file: {e}")
    exit()

# ------------------------------
# STEP 3: Validate the Excel File Format
# ------------------------------
# Ensure the necessary columns exist
if "Original Name" not in df.columns or "New Name" not in df.columns:
    print("Error: The Excel file must contain 'Original Name' and 'New Name' columns.")
    exit()

# ------------------------------
# STEP 4: Iterate Over Rows and Rename Files
# ------------------------------
for index, row in df.iterrows():
    original_name = row["Original Name"]  # Original file name
    new_name = row["New Name"]  # New file name

    # Construct the full file paths
    current_path = os.path.join(directory, original_name)
    new_path = os.path.join(directory, new_name)

    # Rename the file if it exists
    if os.path.exists(current_path):
        try:
            os.rename(current_path, new_path)  # Perform renaming
            print(f"Renamed: {original_name} -> {new_name}")
        except Exception as e:
            print(f"Error renaming {original_name} to {new_name}: {e}")
    else:
        print(f"Warning: File not found - {original_name}")

# ------------------------------
# STEP 5: Confirm Completion
# ------------------------------
print("Renaming process completed successfully!")
input("Press Enter to exit...")
    

To successfully rename files in bulk using Python, follow these steps:

  1. Open Notepad or your preferred text editor.
  2. Copy the Python script (provided above).
  3. Paste it into the editor.
  4. Click File > Save As.
  5. In the “Save as type” dropdown, select “All Files”.
  6. Name the file with a .py extension, such as file-renaming.py, ensuring it’s not saved as .txt.
  1. Create an Excel Sheet
    • Open Microsoft Excel and create a new spreadsheet.
  2. Define the Column Headers
    • In Cell A1, type: Original Name
    • In Cell B1, type: New Name
  3. Enter File Names
    • In Column A (Original Name), list the exact current names of the files (including extensions like .txt, .jpg, .pdf).
    • In Column B (New Name), enter the desired new names (also with extensions).
    • If extensions are missing, the Python script will not work.
  4. Save the Excel File
    • Click File > Save As.
    • Name the file file-renaming.xlsx and save it as an Excel Worksheet (.xlsx).
    • Close the Excel file.
  5. Place the Excel Sheet in the Script Folder
    • Ensure file-renaming.xlsx is stored in the same folder as file-renaming.py.
  1. Double-click file-renaming.py to execute it.
  2. When prompted, enter the directory where the files to be renamed are located.
  1. Open the folder containing the files.
  2. Check if the files were renamed correctly based on the Excel sheet.

Manually typing file names is tedious. Below are two quick ways to generate a list of file names automatically.

Use this Python script to list all files in a directory and export them to an Excel sheet.


import os
import pandas as pd

# ------------------------------
# STEP 1: Prompt User for Directory
# ------------------------------
directory = input("Enter the folder path you want to list files from: ")

# Ensure the directory exists
if not os.path.isdir(directory):
    print("Error: Invalid directory path. Please check and try again.")
    exit()

# ------------------------------
# STEP 2: Retrieve File Names
# ------------------------------
file_names = os.listdir(directory)  # Get a list of files in the directory

# ------------------------------
# STEP 3: Create a DataFrame
# ------------------------------
df = pd.DataFrame(file_names, columns=["File Names"])

# ------------------------------
# STEP 4: Save to Excel File
# ------------------------------
output_excel = os.path.join(directory, "file_list.xlsx")

try:
    df.to_excel(output_excel, index=False)  # Save the DataFrame to an Excel file
    print(f"File list successfully saved to: {output_excel}")
except Exception as e:
    print(f"Error saving to Excel: {e}")

# ------------------------------
# STEP 5: Completion Message
# ------------------------------
input("Press Enter to exit...")
    
  1. Open Notepad or any text editor.
  2. Copy and paste the script into the editor.
  3. Click File > Save As.
  4. In the “Save as type” dropdown, select “All Files”.
  5. Name the file generate-file-list.py (not .txt).
  6. Double-click the saved file to run it.
  7. Enter the directory path where your files are stored.
  8. The script will create an Excel file named file_list.xlsx in the same directory.

You can use Excel’s built-in feature to automatically list file names.

  1. Open Microsoft Excel
    • Start a new Worksheet.
  2. Use the “Get Data” Function
    • Click on the Data tab in the Excel ribbon.
    • Select Get Data > From File > From Folder.
  3. Select Your Folder
    • Browse to the folder containing the files.
    • Click OK.
  4. Load File Names into Excel
    • A Navigator Window will appear—click Transform Data.
    • In Power Query Editor, delete unnecessary columns (keep only “Name”).
    • Click Close & Load to insert file names into Excel.
  5. Move File Names into the File-Renaming Sheet
    • Copy the imported file names to Column A (Original Name) of file-renaming.xlsx.

Windows File Explorer has a quick built-in method to rename files in bulk.

  1. Open File Explorer
    • Navigate to the folder containing your files.
  2. Switch to Details View
    • Click on the View tab in File Explorer.
    • Select Details view to display file attributes.
  3. Select All Files
    • Press Ctrl + A to highlight all files.
  4. Initiate Rename
    • Right-click any selected file and click Rename.
  5. Enter a New Name
    • Type a common name, such as "file", and press Enter.
  6. Windows Will Automatically Number Files
    • The renamed files will follow this format:
      • file (1).txt
      • file (2).txt
      • file (3).txt

This guide provides easy solutions to batch rename files.

Use Python for automated file renaming.
Use Excel to list file names without coding.
Use File Explorer for quick bulk renaming.

These methods save time, reduce errors, and improve efficiency when organizing large numbers of files.

This article is for informational and entertainment purposes only and does not constitute professional advice. Please consult a qualified professional for your specific needs. Swirly Sky Ventures LLC assumes no responsibility or liability for any actions taken based on the information provided in this article. For more details, please review our Terms of Use.

Google Lighthouse logo with a red lighthouse and text on a blue background, representing website performance and SEO audit tool.

Audit Your Website Performance with Google Lighthouse

Audit your website’s speed, SEO, and user experience using Google Lighthouse. Learn step-by-step optimization strategies for peak performance!

Laptop displaying website speed analytics with neon digital performance icons, including an SEO graph, image optimization symbol, and security lock, in a glowing cyber-themed environment.

Boost website speed, SEO rankings, and user experience. Learn how to optimize image properties for better performance and user engagement.