In this tutorial, you will learn how to rename files and folders in Python.
After reading this article, you’ll learn: –
- Renaming a file with rename() method
- How to rename single and multiple files.
- Renaming files that match a pattern
- Renaming all the files in a folder
- Renaming only the files in a list
- Renaming and moving a file
Table of contents
- Steps to Rename File in Python
- Rename a file after checking whether it exists
- Rename Multiple Files in Python
- Renaming only a list of files in a folder
- Renaming multiple files with a pattern
- Renaming files with a timestamp
- Renaming the Extension of the Files
- Renaming and then moving a file to a new location
- Practice Problem: Renaming an image file
Steps to Rename File in Python
To rename a file, please follow these steps:
- Find the path of a file to rename
To rename a file, we need its path. The path is the location of the file on the disk.
An absolute path contains the complete directory list required to locate the file.
A relative path contains the current directory and then the file name. - Decide a new name
Save an old name and a new name in two separate variables.
old_name = 'details.txt'
new_name = 'new_details.txt'
- Use rename() method of an OS module
Use the
os.rename()
method to rename a file in a folder. Pass both the old and new names to theos.rename(old_name, new_name)
function to rename a file.
os.rename()
We can rename a file in Python using the rename
() method available in the os module. The os
module provides functionalities for interacting with the operating systems. This module comes under Python’s standard utility modules.
os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Code language: Python (python)
The following are the parameters that we need to pass for the os.rename()
method
src
: Path for the file that has to be renameddst
: A destination path for the newly renamed filesrc_dir_fd
: (Optional) Source file directorydst_dir_fd
: (Optional) Destination file directory
Note: If the dst
already exists then the FileExistsError
will be thrown in Windows and in the case of UNIX an OSError
will be thrown.
Example: Renaming a file in Python
In this example, we rename “detail.txt” to “new_details.txt”.
Output:
Before rename
After rename
Rename a file after checking whether it exists
The os.rename()
method raises the FileExistsError or OSError when the destination file name already exists. This can be avoided by wrapping our code in the try-except
block.
Use the isfile(‘path’) function before renaming a file. It returns true if the destination file name already exists.
We can use the following two approaches to continue with renaming by removing the old file or stop without renaming it.
- Use
os.path.isfile()
in anif
condition - Write rename code in the try-except block.
Example 1: Use os.path.isfile()
Output
File name already exists. Cannot rename
Example 2: The same code could be wrapped in the try-except block as below.
Output:
File already Exists Removing existing file Done renaming a file
Rename Multiple Files in Python
Sometimes, we need to rename all files from a directory. Consider a folder with four files with different names, and we wanted to rename all file names.
We can rename multiple files in a folder using the os.listdir()
and os.rename()
method by following the below steps.
- Get the list of files in a directory using
os.listdir()
. It returns a list containing the names of the entries in the given directory. - Iter over the list using a for loop to access each file individually.
- Rename each file
Example: Change the names of all files from a directory
Output
All Files Renamed New Names are ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
Renaming only a list of files in a folder
While renaming files inside a folder, sometimes we may have to rename only a list of files, not all. We need to follow the following steps for renaming only a set of files inside a folder.
- Providing the list of files that need to be renamed
- Iterate through the list of files in the folder containing the files
- Check if the file is present in the list
- If present, rename the file according to the desired convention. Else, move to the next file.
Example: Renaming only a specific files in a folder
Output
['sales_1_new.txt', 'sales_2.txt', 'sales_3.txt', 'sales_4_new.txt']
Renaming multiple files with a pattern
Sometimes, we wanted to rename only those files that match a specific pattern. For example, renaming only pdf files or renaming files containing a particular year in their name.
The pattern matching is done using the glob module. The glob module finds the files and folders whose names follow a specific pattern. We can rename multiple files that match a pattern using the glob module.
We can rename files that match a pattern using the following steps: –
- Write a pattern using wildcard characters
- Use a glob() method to find a list of files that matches a pattern.
- Iterate through the files in the folder.
- Change the name according to the new naming convention.
Example: Renaming files that follow specific name patterns
In this example, we rename all text files starting with the word “sales” inside the “reports” folder with the new name “revenue” and a counter.
Output
E:\demos\files\reports\revenue_1.txt E:\demos\files\reports\revenue_2.txt
Renaming files with a timestamp
In some applications, the data or logs will be stored in the files regularly in a fixed time interval. It is a standard convention to append a timestamp to file names to make them easy to store and use later. We can use the datetime module in Python to work with dates and times.
Please follow the below steps to append the timestamp to the file name:
- Get the current timestamp using a datetime module and store it in a separate variable
- Convert timestamp into a string
- Append timestamp to file name by using the concatenation operator
- Now, rename a file with a new name using a
os.rename()
Consider the following example where we add the timestamp in the %d-%b-%Y
format.
Example: Renaming files with a timestamp
Renaming the Extension of the Files
We can change only the extension of the files using the rename()
method. This is done by getting the list of the files and then get only the file name using the splitext() method of the os module.
This method returns the root and extension separately. Once we get the root/base of the filename, we can add the new extension to it while renaming it using the rename()
method
Use the below steps to rename only extension: –
- Get List file names from a directory using a
os.listdir(folder)
- Next, Iterate each file from a list of filenames
- Construct current file name using
os.path.join()
method by passing file name and path - Now, use the
replace()
method of astr
class to replace an existing extension with a new extension in the file name - At last, use the
os.rename()
to rename an old name with a new name
Let’s see the example.
Output
Before rename ['expense.txt', 'profit.txt', 'revenue_1.txt', 'revenue_2.txt'] After rename ['expense.pdf', 'profit.pdf', 'revenue_1.pdf', 'revenue_2.pdf']
Renaming and then moving a file to a new location
With the help of the rename()
method we can rename a file and then move it to a new location as well. This is done by passing the new location to the rename()
method’s dst
parameter.
Consider the below example where we are defining two different folders as the source and destination separately. Then using the rename() method,
we are changing the name and the location of the file.
Finally when we print the files in the new location we can see the file in the list.
Practice Problem: Renaming an image file
We can rename any file in a folder and files of any type using the os.rename()
. In the below example we will change the name of an image file inside the folder.
Output
['/Users/sample/eclipse-workspace/Sample/Files/Images/Emp_2.jpg', '/Users/sample/eclipse-workspace/Sample/Files/Images/Emp_1.jpg']
In this article we have covered the basics of renaming a file, the method used for renaming. We also saw how to rename a file with a particular pattern, naming all the files in a folder and adding a date to the file. We also with example how to change the extension of the file and how to move a file to a new location after changing the name.