Do you have a folder with messed up file names β like IMG_1234.jpg
, File(7).txt
or New Document.docx
?
If you try to rename them one by one, it will take hours. But donβt worry, Python can do this in just a few seconds. Just follow this guide and you will be able to rename your files automatically.
In this guide, we will create a python script that will rename all the files in a folder at once. Whether the folder contains photos, or scattered files in Downloads, everything will become clean and organized.
Before vs After Example
Let's see the kind of a difference this script can make.
π BEFORE:
- IMG_1234.jpg
- IMG_1235.jpg
- IMG_1236.jpg
π AFTER (with prefix = Vacation):
- Vacation_1.jpg
- Vacation_2.jpg
- Vacation_3.jpg
Prerequisites
- A folder containing the files you want to rename.
- Python installed on your computer. If you don't have it, follow this python installation guide and install.
Step 1: Set up your workspace
1. Create a new folder:
Create a new folder on your desktop, name it Rename_Files_Project
.

2. Add your files:
Put the files you want to rename into this folder. For example, you have some image files β IMG_1234.jpg
, IMG_1235.jpg
, etc. β put them all here.

3. Create a Python file:
Now open any text editor like Notepad, VS Code, or Sublime Text. Create a blank file in the editor and save it in the same "Rename_Files_Project" folder you just created. Name this file: rename_script.py

Step 2: Write a Python script
Open the file named rename_script.py
and copy-paste the following code into it:
import os
import re
# This function renames all files in a folder with a new name.
def rename_files(folder_path, prefix):
"""
This function renames all files in a given folder by giving them a new prefix and serial number.
Args:
folder_path (str): The folder where the files are stored.
prefix (str): The new prefix to be added to the name of each file (e.g. 'Vacation').
"""
try:
# Get a list of all the items in the folder.
files = os.listdir(folder_path)
# Keep only files from the list and remove folders.
files = [f for f in files if os.path.isfile(os.path.join(folder_path, f))]
# Sort the files so that the serial numbers are in the correct order.
files.sort()
# Now rename each file one by one.
for index, filename in enumerate(files, 1):
# Separate the file name and its extension.
name, extension = os.path.splitext(filename)
# Create a new name: prefix + serial number + extension
new_filename = f"{prefix}_{index}{extension}"
# Create the old and new file paths.
old_filepath = os.path.join(folder_path, filename)
new_filepath = os.path.join(folder_path, new_filename)
# Now give the file a new name.
os.rename(old_filepath, new_filepath)
print(f"Renamed '{filename}' to '{new_filename}'")
print("\nAll files have been renamed successfully!")
except FileNotFoundError:
print(f"Error: The given folder ('{folder_path}') was not found.")
except Exception as e:
print(f"Something went wrong: {e}")
# Here you will tell which folder to rename and what will be the new name.
# '.' means the folder where this script is currently running.
folder_to_rename = '.'
new_prefix = 'Vacation'
# The script starts with the below line.
if __name__ == "__main__":
rename_files(folder_to_rename, new_prefix)
Step 3: Modify the script to suit your needs
In this step, you only need to adjust two lines of the script so that it works for your purpose:
folder_to_rename = '.'
This line contains the name of the folder where your files are stored. If you leave out just the.
, it means that the script will run on the same folder where the script itself is stored. That is, if you have followed step 1 correctly, you won't need to change anything. But if your files are located somewhere else, replace the.
with the full path of that folder. For example:'C:\\Users\\YourName\\Pictures\\PhotosToRename'
new_prefix = 'Vacation'
This line determines what the new name of your files will be. In place of'Vacation'
, write whatever name you want. Such as:'My_Docs'
,'Project_Files'
,'College_Notes'
etc. Then your files will be named something like this:My_Docs_1.jpg
,My_Docs_2.jpg
,My_Docs_3.jpg
... and so on.
Step 4: Run the script
π Tip: Make a copy of your files before running the script β safety first!
First, open your command prompt:
- If you're running on Windows, press
Win + R
, then typecmd
and pressEnter
. - If you have macOS or Linux, open the Terminal.
Now go to the folder where your project is located β named Rename_Files_Project
. Use the cd
command to do this:

Example:
cd C:\Users\YourName\Desktop\Rename_Files_Project
Now that you're in the right directory, run the Python script:
python rename_script.py
Press Enter
.
The script will run and display a message for each file it's renaming. When all files are finished, you will get a confirmation message and all files will be renamed with the prefix and numbering you provided.

Bonus Tip: Rename Specific File Types
Do you only want files in .jpg
format to be renamed?
So you can add a small condition inside your for loop to only work on .jpg
files - skipping all others. Just add this line at the start of the for loop:
if not filename.lower().endswith('.jpg'):
continue
This means - if the file name does not end in .jpg
, skip it and move on to the next one. This will make your script select only the files you want.
Frequently Asked Questions (FAQs)
1. What if I want the numbering to start from 100 instead of 1? For example Vacation_100.jpg
?
No problem. The β1β in the script enumerate(files, 1)
means that the counting starts from 1. If you want to start from 100, just change it to enumerate(files, 100)
.
2. My files got renamed in the wrong order (e.g. 1, 10, 11, 2)? Why did this happen?
Because the computer treats numbers as text in normal sorting. So it puts β10β before β2β (alphabetical logic). Solution: Use a sorting method that recognizes numbers correctly. Below is a small piece of code that does just that:
import re
def extract_number(filename):
s = re.findall(r'\d+', filename)
return int(s[0]) if s else -1
# Modify files.sort():
files.sort(key=extract_number)
This method extracts a number from each filename and arranges the files in the correct order.
3. What if I want to rename files in another folder, but want the script to remain the same?
So change folder_to_rename = '.'
to give the full path of that folder. For example: folder_to_rename = 'C:\\Users\\YourName\\Documents\\MyPhotos'
. Just remember - in Windows, it is necessary to use double backslashes (\\
) when typing the path.