What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Rename File in Python? (with OS module)

  • Nov 15, 2023
  • 5 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
How to Rename File in Python? (with OS module)

Python is a powerful and dynamic language that allows us to perform a plethora of actions and operations. A much-needed set of operations in python is file handling. It is important as files are the basic building block of any system. In this article, we will learn a fundamental action in file handling, how to rename files with code. Before we dive into let us have a brief about what are files and why we need to rename them.

Why do we need to Rename Files?

A file is a grouping of data or information stored on a computer or electronic device. They are typically saved with a specific file extension, such as .txt for text files, .jpg for images, and .mp3 for audio files, to assist the operating system and other software in determining the type of file and how to open or process it.

In Python, a file is an object that contains a collection of data, stored on a disk with a specific name and file path. We can read, write, and append data to the file.

We may need to rename files for a variety of reasons:

  1. To be more descriptive or meaningful, or to follow a naming convention
  2. Organize them by grouping similar files together.
  3. Avoid having duplicate file names.
  4. Make it difficult for others to identify its contents for security reasons.
  5. Efficient management of large amounts of data by making them easier to find.

So, in short, renaming files can help us keep organized, enhance productivity, and make it easier to discover and use the files we need, whether we're working on a personal or business project.

Files can be renamed in python using the os module. Let us discuss in detail the os module before moving forward.

What is the OS module?

Python's OS module supports a variety of file system interaction operations, such as creating, renaming, and removing files and directories.

For example, the os.listdir() method, which returns a list of files and directories in a specified directory, is one of the most widely used functions in the OS module.  This module also includes the os.path submodule, which offers a number of file path-related functions.  The os.chmod() function can be used to change a file's permissions.

Python's OS module is a strong tool for interfacing with the operating system and file system. It has a lot of features for working with files and directories, file paths, environment variables, and other low-level features. Developers frequently utilize this module to automate activities, manage files and directories, and execute various other operations on the operating system.

How to Rename a file in Python?

Renaming files in Python is done using os.rename() function in the OS module. It takes two arguments: the current name of the file or directory and the new name. 

The following is the fundamental syntax:

os.rename(current_file_name, new_file_name)


It should be noted that the os.rename() function only works with files and folders in the same directory. If you want to rename a file or directory in another directory, include the entire path to the file or directory in both the current and new file name parameters.

Assume you want to rename a file named "old file.txt" to "new file.txt". The following code can be used:

import os

os.rename("old_file.txt", "new_file.txt")


Renaming Multiple Files at Once

You can use a loop to iterate through a list of file names and execute the os.rename() function for each file if you want to rename numerous files at once.

import os

old_file_names = ["old_file1.txt", "old_file2.txt", "old_file3.txt"]

new_file_names = ["new_file1.txt", "new_file2.txt", "new_file3.txt"]

for i in range(len(old_file_names)):

os.rename(old_file_names[i], new_file_names[i])


It is vital to remember that if the file you are attempting to rename does not exist, the os.rename() function will throw a FileNotFoundError. To handle this issue, a try-except block can be used to capture the problem and print a message to the user.

import os


os.rename(old_file_name, new_file_name)

except FileNotFoundError:

print(f"{old_file_name} does not exist.")


Pattern-based File Renaming

Python also provides the glob module, allowing us to rename files that match a specific pattern. This is particularly useful when you need to rename only a subset of files in a directory.

import os

path = "path/to/dir/"
pattern = path + "*.txt"
result = glob.glob(pattern)

count = 1
for filename in result:
    old_name = filename
    new_name = path + 'newfile_' + str(count) + ".txt"
    os.rename(old_name, new_name)
    count += 1


In this example, we're renaming all text files in the specified directory by replacing the old filename with a new one prefixed by "newfile_" and suffixed with a counter.

Renaming Files with Timestamps

Appending timestamps to filenames is a common practice, especially when dealing with logs or data files. Python's datetime module helps us achieve this.

import os
from datetime import datetime

current_timestamp = datetime.today().strftime('%d-%b-%Y')
old_name = "path/to/dir/oldfile.txt"
new_name = "path/to/dir/" + "newfile_" + current_timestamp + ".txt"
os.rename(old_name, new_name)


In the above example, we're appending the current date in the "dd-MMM-yyyy" format to the new filename.

Changing File Extensions

The os.rename() function can also change the extension of files. To achieve this, we separate the filename from its extension using the os.path.splittext() method.

import os

folder = "path/to/dir/"
for filename in os.listdir(folder):
    old_name = os.path.join(folder, filename)
    base = os.path.splitext(old_name)[0]
    os.rename(old_name, base + ".pdf")


In this example, we're converting all ".txt" files in the specified directory to ".pdf" format.

Renaming and Moving Files

The os.rename() function can also move files to a new location while renaming them. This is achieved by specifying a destination directory in the "dst" argument.

import os

old_folder = "path/to/old_dir/"
new_folder = "path/to/new_dir/"
old_name = old_folder + "oldfile.txt"
new_name = new_folder + "newfile.txt"
os.rename(old_name, new_name)


In this example, we're moving "oldfile.txt" from the old directory to the new directory, while renaming it to "newfile.txt".

Also, you can check out how to delete a file in python.


When renaming files, it is critical to check whether the new file name already exists or not, as it will replace any existing file with the same name without warning. The Python OS module makes it simple and efficient to rename files. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.