Being able to work with files is an essential skill for a Python developer of any skill level. In particular, Python can be used to easily rename a single file or multiple files. Being able to automate repetitive tasks, such as renaming files can save you a ton of time. In this tutorial, you’ll learn how to rename files with Python using the os.rename() function.
By the end of this tutorial, you’ll have learned the following:
- How to use the Python
os.rename()
function - How to rename a single file or multiple files at once
- How to rename files matching a pattern, such as modifying the date pattern in multiple files
- Handling errors when renaming files with Python
Table of Contents
Understanding the Python os.rename() Function
Python comes with a built-in function, rename()
, as part of the os
library. As the name implies, the function is used to rename a file. Before diving into how practical examples, let’s take a look at what makes up the function, including its various parameters:
# Understanding the Python os.rename() Function
os.rename(
src,
dst,
*,
src_dir_fd=None,
dst_dir_fd=None
)
From the code block above, you can see that the function accepts four arguments, two of which are optional. Let’s take a look at the parameters of the os.rename()
function, including their default arguments:
Parameter | Description | Default Argument | Accepted Values |
---|---|---|---|
src= | The path for the file that you want to rename | string or path-like | |
dst= | The destination path for the file that you want to use | string or path-like | |
src_dir_fd= | The source file directory | None | string or path-like |
dst_dir_fd= | The destination file directory | None | string or path-like |
Now that you have a strong understanding of how the function works, let’s dive into some practical examples of how to rename files with Python.
How to Rename a File with Python Using os.rename()
In order to rename a file with Python, you can use the os.rename() function. Simply pass in both the source path to the file and the updated file path that you want to use. If the renamed file path already exists, then Python will raise a FileExistsError.
Let’s take a look at an example of how to rename a file with Python.
# Rename a File with Python os.rename()
import os
os.rename('old_name.txt', 'new_name.txt')
Let’s take a look at how we can rename a file using the Python os.rename() function:
- Import the os library
Import the os library using
import os
which will give you access to the os.rename() function - Enter the original file path as the first argument in the os.rename() function
The os.rename() function accepts two required arguments: the original, source file path and the destination file path. Enter the source file path into the first position argument.
- Enter the renamed file path into the second argument in the os.rename() function
Enter the renamed file path into the second argument. If the file path already exists, Python will raise a FileExistsError and the program won’t complete.
Now that you know how to rename a single file, let’s take a look at how you can use Python to rename multiple files at once.
How to Rename Multiple Files with Python Using os.rename()
To rename multiple files using Python, you can combine the os.rename() function with a Python for loop. A for loop lets you iterate over a list of items, such as a list of file names.
If you want to rename all the files in a directory, you can use the os.listdir() function to get a list of all of the files in a directory. Let’s see how we can use a for loop and the os.rename() function to rename all files in a folder by adding a prefix of "old_"
:
# Rename Multiple Files with Python
import os
dir = 'files/'
for file in os.listdir(dir):
old_filepath = os.path.join(dir, file)
new_name = 'old_' + file
new_filepath = os.path.join(dir, new_name)
os.rename(old_filepath, new_filepath)
Let’s break down what we’re doing in the code block above:
- We create a new variable for our directory,
dir
. In this case, it holds the relative path to our directory, assuming that we’re working in the same directory. - We then loop over each file in the directory and do the following
- We create a variable called
old_filepath
that represents the path to the files - We create a new name for each file by pretending
'old_'
to the file - We then join the directory and new name together
- We create a variable called
- Finally, we use the
os.rename()
function to rename each file in the folder
In the following section, you’ll learn how to rename files in a folder matching a timestamp pattern.
How to Rename Files Matching a Timestamp Pattern Using Python
In many cases, files will have a timestamp or date pattern in them. However, in some cases, these date patterns won’t be structured in a way that’s useful to you. This is where being able to rename files using Python comes in handy! Being able to rename hundreds or thousands of files to change their date and time pattern is an incredibly useful skill.
Let’s take a look at an example. Say we have a folder of files that contain the following files:
- file_01-01-2023.txt
- file_02-01-2023.txt
- file_03-01-2023.txt
- file_04-01-2023.txt
We can see that these files have a date appended to them. The pattern for these dates are MM-DD-YYYY. Say you want to change the format to be the more common YYYY-MM-DD format. Let’s see how we can do this with Python:
# Rename Files with a Date Pattern
import os
import re
from datetime import datetime
dir = 'date_files/'
for file in os.listdir(dir):
old_filename = os.path.join(dir, file)
old_date = re.search(r'\d{2}-\d{2}-\d{4}', file).group()
new_date = datetime.strptime(old_date, '%M-%d-%Y').strftime('%Y-%M-%d')
new_file = file.replace(old_date, new_date)
new_filename = os.path.join(dir, new_file)
os.rename(old_filename, new_filename)
This example is a bit more complicated so let’s break down what we’re doing step by step:
- We import the os, re, and datetime.datetime libraries
- We then declare our
dir
variable as before - When we loop over the files, we search for the old date pattern by using the
re.search()
method - We then use the strptime and strftime functions to first load the date pattern as a date and then modify if to our desired pattern
- Finally, we create our new file path and rename the files using the os.rename() function
In the final section below, you’ll learn how to handle errors when renaming files with Python.
How to Handle Errors When Renaming Files with Python
When trying to rename a file that doesn’t exist with Python, a FileNotFounderror
will be raised. This indicates that the file doesn’t exist and will crash your program unless it’s handled appropriately.
Let’s take a look at what this error looks like:
# Raising a FileNotFoundError
import os
os.rename('thisfiledoesnotexist.txt', 'newname.txt')
# Returns:
# FileNotFoundError: [Errno 2] No such file or directory: 'thisfiledoesnotexist.txt' -> 'newname.txt'
We can see from the code above that the program crashed when we attempted to rename the file. In order to handle this error safely and keep the program running, we can wrap everything in a try-else block.
Let’s take a look at what this looks like:
# Handling a FileNotFoundError
import os
try:
os.rename('thisfiledoesnotexist.txt', 'newname.txt')
except FileNotFoundError:
print('File does not exist.')
# Returns: File does not exist.
We can see that by using a try-else block, we were able to handle the specific error raised when a file doesn’t exist. In this case, our program continues to run and lets the user know that the file doesn’t exist.
Conclusion
In this tutorial, you learned how to rename files using Python. Because Python is a general purpose programming language, it can be used to automate mundane tasks, such as working with files. You first learned how the os.rename() function works by exploring its different parameters and default arguments. Then, you learned how to rename a single file and multiple files. From there, you learned how to rename date patterns in files to meet your needs. Finally, you learned how to handle FileNotFoundErrors that arise when using the os.rename() function when a file doesn’t exist.
Additional Resources
To learn more about related topics, check out the tutorials below: