How to Rename a File Using Python

In this tutorial, we’ll learn how to rename a file in Python using the os module.

The os module provides a set of functions to perform a variety of operations on files and directories, including renaming files.

We’ll start by explaining the basic concepts of file manipulation in Python and then show you how to rename a file with Python code examples.


Step 1: Import the os Module

To begin, we need to import the os module into our Python code.

This module provides a variety of functions that make it easy to work with files and directories in Python.

import os

Step 2: Use the os.rename() Function

The os.rename() function is used to rename a file in Python. It takes two arguments: the current name of the file and the new name of the file.

Here’s an example of how you can use this function to rename a file in Python:

os.rename("old_file_name.txt", "new_file_name.txt")

In this example, the os.rename() function takes two arguments: “old_file_name.txt” and “new_file_name.txt”.

The first argument is the current name of the file, and the second argument is the new name of the file.

Step 3: Exception Handling

It’s always a good idea to handle exceptions when working with files in Python.

For example, if the file you’re trying to rename doesn’t exist, the os.rename() function will raise a FileNotFoundError exception.

To handle this exception, you can use a try-except block in your code:

try:
os.rename("old_file_name.txt", "new_file_name.txt")
except FileNotFoundError:
print("File not found.")

In this example, the try block contains the os.rename() function, and the except block contains a message that will be displayed if a FileNotFoundError exception is raised.

Step 4: Verify the File Renaming

To verify that the file has been renamed, you can use the os.path.exists() function.

This function takes a file name as an argument and returns True if the file exists and False if it doesn’t. Here’s an example:

if os.path.exists("new_file_name.txt"):
print("File renamed successfully.")
else:
print("File not found.")

In this example, the os.path.exists() function takes the new name of the file as an argument and returns True if the file exists.

If the file exists, a message is displayed indicating that the file has been renamed successfully.


Conclusion

In this tutorial, we learned how to rename a file in Python using the os module.

We explained the basic concepts of file manipulation in Python and showed you how to use the os.rename() function to rename a file.

We also covered exception handling and how to verify that the file has been renamed successfully.

With this knowledge, you should now be able to rename files in Python with ease.