Batch File Renaming with Python

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.
Python Script for Automated File Renaming: file-renaming.py
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...")
How to Save and Run the Python Script for File Renaming
To successfully rename files in bulk using Python, follow these steps:
Copy & Paste the Python Script
- Open Notepad or your preferred text editor.
- Copy the Python script (provided above).
- Paste it into the editor.
- Click File > Save As.
- In the “Save as type” dropdown, select “All Files”.
- Name the file with a
.py
extension, such asfile-renaming.py
, ensuring it’s not saved as.txt
.
Prepare the Excel Sheet with File Names
- Create an Excel Sheet
- Open Microsoft Excel and create a new spreadsheet.
- Define the Column Headers
- In Cell A1, type:
Original Name
- In Cell B1, type:
New Name
- In Cell A1, type:
- 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.
- In Column A (Original Name), list the exact current names of the files (including extensions like
- 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.
- Place the Excel Sheet in the Script Folder
- Ensure
file-renaming.xlsx
is stored in the same folder asfile-renaming.py
.
- Ensure
Run the Script
- Double-click
file-renaming.py
to execute it. - When prompted, enter the directory where the files to be renamed are located.
Verify the Renamed Files
- Open the folder containing the files.
- Check if the files were renamed correctly based on the Excel sheet.
How to Generate a List of Original File Names for Bulk Renaming
Manually typing file names is tedious. Below are two quick ways to generate a list of file names automatically.
Option 1: Generate a File List Using Python
Use this Python script to list all files in a directory and export them to an Excel sheet.
Python Script to Generate an Excel File List: generate-file-list.py
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...")
How to Use This Script
- Open Notepad or any text editor.
- Copy and paste the script into the editor.
- Click File > Save As.
- In the “Save as type” dropdown, select “All Files”.
- Name the file
generate-file-list.py
(not.txt
). - Double-click the saved file to run it.
- Enter the directory path where your files are stored.
- The script will create an Excel file named
file_list.xlsx
in the same directory.
Option 2: Use Microsoft Excel’s “Get Data from Folder” Feature
You can use Excel’s built-in feature to automatically list file names.
Steps to Import File Names into Excel
- Open Microsoft Excel
- Start a new Worksheet.
- Use the “Get Data” Function
- Click on the Data tab in the Excel ribbon.
- Select Get Data > From File > From Folder.
- Select Your Folder
- Browse to the folder containing the files.
- Click OK.
- 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.
- Move File Names into the File-Renaming Sheet
- Copy the imported file names to Column A (Original Name) of
file-renaming.xlsx
.
- Copy the imported file names to Column A (Original Name) of
No-Code Option: Bulk Rename Files Using File Explorer
Windows File Explorer has a quick built-in method to rename files in bulk.
Steps to Bulk Rename Files in Windows
- Open File Explorer
- Navigate to the folder containing your files.
- Switch to Details View
- Click on the View tab in File Explorer.
- Select Details view to display file attributes.
- Select All Files
- Press Ctrl + A to highlight all files.
- Initiate Rename
- Right-click any selected file and click Rename.
- Enter a New Name
- Type a common name, such as
"file"
, and press Enter.
- Type a common name, such as
- Windows Will Automatically Number Files
- The renamed files will follow this format:
file (1).txt
file (2).txt
file (3).txt
- The renamed files will follow this format:
Final Thoughts
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.
Related Posts

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!

Website Image Optimization: Speed and SEO Rank
Boost website speed, SEO rankings, and user experience. Learn how to optimize image properties for better performance and user engagement.