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
- Renaming files that matches 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 files with a timestamp
- Renaming files with a Pattern
- 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
os.rename()method to rename a file in a folder. Pass both the old name and a new name to the
os.rename(old_name, new_name)function to rename a file.
Example: Renaming a file in Python
In this example, we are renaming “detail.txt” to “new_details.txt”.
import os # Absolute path of a file old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" # Renaming the file os.rename(old_name, new_name)
As shown in the example, 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)
The following are the parameters that we need to pass for the
src: Path for the file that has to be renamed
dst: A destination path for the newly renamed file
src_dir_fd: (Optional) Source file directory
dst_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.
Rename a file after checking whether it exists
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
Use the isfile(‘path’) function before renaming a file. It returns true if the destination file already exists.
We can use the following two approaches to continue with renaming by removing the old file or stop without renaming it.
- Write rename code in the try-except block.
Example 1: Use
import os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile(new_name): print("The file already exists") else: # Rename the file os.rename(old_name, new_name)
The file already exists
Example 2: The same code could be wrapped in the try-except block as below.
import os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" # enclosing inside try-except try: os.rename(old_name, new_name) except FileExistsError: print("File already Exists") print("Removing existing file") # skip the below code # if you don't' want to forcefully rename os.remove(new_name) # rename it os.rename(old_name, new_name) print('Done renaming a file')
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.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.
- Iterate over the list using a loop to access each file one by one
- Rename each file
The following example demonstrates how to change the names of all the files from a directory.
import os folder = r'E:\demos\files\reports\\' count = 1 # count increase by 1 in each iteration # iterate all files from a directory for file_name in os.listdir(folder): # Construct old file name source = folder + file_name # Adding the count to the new file name and extension destination = folder + "sales_" + str(count) + ".txt" # Renaming the file os.rename(source, destination) count += 1 print('All Files Renamed') print('New Names are') # verify the result res = os.listdir(folder) print(res)
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 files. The following are the steps we need to follow for renaming only a set of files inside a folder.
- Providing the list of files that needs 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
import os files_to_rename = ['sales_1.txt', 'sales_4.txt'] folder = r"E:\demos\files\reports\\" # Iterate through the folder for file in os.listdir(folder): # Checking if the file is present in the list if file in files_to_rename: # construct current name using file name and path old_name = os.path.join(folder, file) # get file name without extension only_name = os.path.splitext(file) # Adding the new name with extension new_base = only_name + '_new' + '.txt' # construct full file path new_name = os.path.join(folder, new_base) # Renaming the file os.rename(old_name, new_name) # verify the result res = os.listdir(folder) print(res)
['sales_1_new.txt', 'sales_2.txt', 'sales_3.txt', 'sales_4_new.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 name to make them easy for storing and using later. In Python, we can use the datetime module to work with dates and times.
Please follow the below steps to append timestamp to 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
Consider the following example where we are adding the timestamp in the “%d-%b-%Y” format .
import os from datetime import datetime # adding date-time to the file name current_timestamp = datetime.today().strftime('%d-%b-%Y') old_name = r"E:\demos\files\reports\sales.txt" new_name = r"E:\demos\files\reports\sales" + current_timestamp + ".txt" os.rename(old_name, new_name)
Renaming 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 is used to find the files and folders whose names follow a specific pattern.
We can rename files that match a pattern using the following steps: –
- Write a pattern using wildcard characters
- Use a glob() method to find the list of files that matches a pattern.
- Iterate through the files in the folder
- Change the name according to the new naming convention.
Example: Rename all text files starting with the word “sales” inside the “reports” folder with the new name “revenue” and a counter.
import glob import os path = r"E:\demos\files\reports\\" # search text files starting with the word "sales" pattern = path + "sales" + "*.txt" # List of the files that match the pattern result = glob.glob(pattern) # Iterating the list with the count count = 1 for file_name in result: old_name = file_name new_name = path + 'revenue_' + str(count) + ".txt" os.rename(old_name, new_name) count = count + 1 # printing all revenue txt files res = glob.glob(path + "revenue" + "*.txt") for name in res: print(name)
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
Use the below steps to rename only extension: –
- Get List file names from a directory using a
- 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 a
strclass 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.
import os folder = r"E:\demos\files\reports\\" # Listing the files of a folder print('Before rename') files = os.listdir(folder) print(files) # rename each file one by one for file_name in files: # construct full file path old_name = os.path.join(folder, file_name) # Changing the extension from txt to pdf new_name = old_name.replace('.txt', '.pdf') os.rename(old_name, new_name) # print new names print('After rename') print(os.listdir(folder))
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
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.
import glob import os # Old and new folder locations old_folder = r"E:\demos\files\reports\\" new_folder = r"E:\demos\files\new_reports\\" # Old and new file names old_name = old_folder + "expense.txt" new_name = new_folder + "expense.txt" # Moving the file to the another location os.rename(old_name, new_name)
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.
import os import glob folder = "/Users/sample/eclipse-workspace/Sample/Files/Images/" for count, filename in enumerate(os.listdir(folder)): oldname = folder + filename newname = folder + "Emp_" + str(count + 1) + ".jpg" os.rename(oldname, newname) # printing the changed names print(glob.glob(folder + "*.*"))
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.