Python Rename Files in a Folder Example
If you want to rename many files in one folder, Python can do it with a short script.
This beginner-friendly example shows how to:
- loop through files in a folder
- rename each file with a simple pattern
- keep the original file extension
- use
pathlibfor clearer file path handling
This page focuses on one folder only. It does not rename files inside subfolders.
Quick example
from pathlib import Path
folder = Path("example_folder")
for index, file_path in enumerate(folder.iterdir(), start=1):
if file_path.is_file():
new_name = f"file_{index}{file_path.suffix}"
new_path = file_path.with_name(new_name)
file_path.rename(new_path)
print(f"Renamed: {file_path.name} -> {new_path.name}")
This renames each file in the folder to file_1, file_2, and so on, while keeping the original file extension.
What this example does
- Shows how to loop through files in one folder
- Renames each file using a predictable pattern
- Keeps the original file extension
- Uses
pathlibfor beginner-friendly path handling
If you are new to paths, see working with file paths in Python.
How the script works
Here is the same script again:
from pathlib import Path
folder = Path("example_folder")
for index, file_path in enumerate(folder.iterdir(), start=1):
if file_path.is_file():
new_name = f"file_{index}{file_path.suffix}"
new_path = file_path.with_name(new_name)
file_path.rename(new_path)
print(f"Renamed: {file_path.name} -> {new_path.name}")
Step by step:
Path("example_folder")creates a path object for the folderfolder.iterdir()gets the items inside that folderenumerate(..., start=1)gives each item a number starting at 1file_path.is_file()makes sure folders are skippedfile_path.suffixkeeps extensions like.txtor.jpgfile_path.with_name(new_name)builds the new file pathfile_path.rename(new_path)renames the file
Why suffix matters
If your file is named report.txt, then:
print(file_path.suffix)
would give:
.txt
That is why this line keeps the extension:
new_name = f"file_{index}{file_path.suffix}"
Without suffix, report.txt might become just file_1, which removes the original extension.
Example: rename files with numbers
This is the simplest version to learn first.
It is useful when the original file names do not matter.
Code
from pathlib import Path
folder = Path("example_folder")
for index, file_path in enumerate(folder.iterdir(), start=1):
if file_path.is_file():
new_name = f"file_{index}{file_path.suffix}"
new_path = file_path.with_name(new_name)
file_path.rename(new_path)
print(f"Renamed: {file_path.name} -> {new_path.name}")
Example result
If your folder contains:
report.txtphoto.jpgnotes.txt
You might see output like:
Renamed: report.txt -> file_1.txt
Renamed: photo.jpg -> file_2.jpg
Renamed: notes.txt -> file_3.txt
Important note about order
The order from iterdir() is not always guaranteed.
That means report.txt might become file_1.txt on one run, but a different file might get that name on another system.
If you want a more predictable order, sort the files first:
from pathlib import Path
folder = Path("example_folder")
files = sorted(folder.iterdir())
for index, file_path in enumerate(files, start=1):
if file_path.is_file():
new_name = f"file_{index}{file_path.suffix}"
new_path = file_path.with_name(new_name)
file_path.rename(new_path)
print(f"Renamed: {file_path.name} -> {new_path.name}")
If you want to learn more about listing folder contents, see how to list files in a directory in Python.
Example: add a prefix to each file
This version keeps most of the original name.
It is often safer and easier to read.
For example:
notes.txtbecomesold_notes.txtphoto.jpgbecomesold_photo.jpg
Code
from pathlib import Path
folder = Path("example_folder")
for file_path in folder.iterdir():
if file_path.is_file():
new_name = f"old_{file_path.name}"
new_path = file_path.with_name(new_name)
file_path.rename(new_path)
print(f"Renamed: {file_path.name} -> {new_path.name}")
What changed
The key line is:
new_name = f"old_{file_path.name}"
file_path.namegives the full file name, such asnotes.txt- adding
"old_"puts a prefix at the start - the extension stays because the original name stays
This is a good option when you want to rename files but still keep them recognizable.
For renaming just one file, see how to rename a file in Python.
How to avoid accidental problems
Before running a renaming script on real files:
- Test in a folder with sample files first
- Print old and new names before renaming
- Skip folders unless you want to rename them too
- Make sure new names do not duplicate existing names
- Keep backups if the files are important
A very safe practice is to preview the rename first.
Preview before renaming
from pathlib import Path
folder = Path("example_folder")
for index, file_path in enumerate(folder.iterdir(), start=1):
if file_path.is_file():
new_name = f"file_{index}{file_path.suffix}"
new_path = file_path.with_name(new_name)
print(f"Would rename: {file_path.name} -> {new_path.name}")
This prints the planned changes without actually renaming anything.
Common errors when renaming files
Here are some common problems beginners run into.
Wrong folder path
If the folder does not exist, you may get a FileNotFoundError.
Example:
from pathlib import Path
folder = Path("missing_folder")
for file_path in folder.iterdir():
print(file_path)
If you see this kind of error, check:
- the folder name
- the location of your script
- your current working directory
Related help: FileNotFoundError: No such file or directory fix
Permission problems
You may get a PermissionError if:
- the file is open in another program
- the folder is protected
- your account cannot modify the file
Related help: PermissionError: Permission denied fix
Using paths incorrectly
Beginners sometimes build paths with plain strings in a way that breaks on different systems.
Using pathlib helps avoid that problem.
If you use the os module instead, you usually need tools like os.path.join(). See os.path.join() explained and the Python os module overview.
Duplicate target names
If two files end up with the same new name, the rename may fail or replace another file depending on the operating system.
For example, this is risky:
from pathlib import Path
folder = Path("example_folder")
for file_path in folder.iterdir():
if file_path.is_file():
new_path = file_path.with_name("same_name.txt")
file_path.rename(new_path)
Make sure each new name is unique before calling rename().
Unexpected rename order
Folder listings are not always returned in the same order.
If the order matters:
- sort the file list first
- or rename based on the original file names
Beginner debugging checklist
If your script does not work, try printing values before the rename step.
Useful checks:
print(folder)
print(file_path)
print(file_path.is_file())
print(file_path.name)
print(file_path.suffix)
print(new_path)
These help you confirm:
- the folder path is correct
- each item is really a file
- the file name is what you expect
- the extension is being kept
- the new target path looks correct
A good beginner workflow:
- Try with 2 or 3 test files
- Print each file name before renaming
- Print the new name before calling
rename() - Confirm folders are being skipped
- Run the real rename only after the preview looks correct
FAQ
How do I keep the file extension when renaming?
Use file_path.suffix and add it to the new name.
Example:
new_name = f"file_{index}{file_path.suffix}"
Can I rename only .txt files?
Yes. Check the suffix before renaming.
from pathlib import Path
folder = Path("example_folder")
for index, file_path in enumerate(folder.iterdir(), start=1):
if file_path.is_file() and file_path.suffix == ".txt":
new_name = f"file_{index}{file_path.suffix}"
new_path = file_path.with_name(new_name)
file_path.rename(new_path)
print(f"Renamed: {file_path.name} -> {new_path.name}")
Will this rename files inside subfolders too?
No. This example only works on files directly inside one folder.
What if two files get the same new name?
The rename can fail or overwrite depending on the system. Generate unique names first.
Should I use os or pathlib for this?
For beginners, pathlib is usually easier to read and safer to work with.
See also
- How to rename a file in Python
- How to list files in a directory in Python
- Working with file paths in Python
- Python os module overview
- FileNotFoundError: No such file or directory fix
- PermissionError: Permission denied fix
Try the script in a small test folder first. Once that works, move on to learning more about listing files, handling paths, and fixing common file-related errors.