How to Rename a File/Directory in Python?

Python Rename File Directory

Hello, I hope you are doing well! In this article, we will rename a file or directory in Python.


Rename a File/Directory in Python using the os module

Python os module offers various functions to deal and interact with the underlying operating system of the particular device.

Python os.rename() function enable us to rename a file or directory, directly from command prompt or IDE. The os.rename() function alters the name of the source/input/current directory or file to a specified/user-defined name.

Thus, through Python os module, all the system level interactions can be performed.

Now, let us have a look at the syntax of Python os.rename() function.


Syntax of Python os.rename() function

Have a look at the below syntax:

import os
os.rename(source,destination)

In order to use the rename() function, we need to import Python os module.

Further, the following parameters needs to be provided to the rename() function:

  • source: The current name of the file or directory.
  • destination: The name which would replace the current name of file/directory.

The os.rename() function does not return any value. It only renames the specified file/directory.

Having understood the working and syntax of rename() function, let us now implement the same through examples in the below section.


Implementing Python os.rename() function through examples

Let’s try to rename a directory using the os.rename function

Example:

import os
os.chdir(r"C:/Users/HP/OneDrive/Desktop/")

os.rename("Programming","PRACTICE")

print("The Directory has been successfully renamed!")

The os.chdir() function is used to change the current working directory.

Output:

The Directory has been successfully renamed!

Directory after updating the name:

Directory Renamed As PRACTICE
Directory Renamed As PRACTICE

Here, we have renamed the Directory ‘Programming’ to ‘PRACTICE’ using rename() function.

Now, let us try to rename a file using Python os.rename() function.

Example:

import os

os.rename("C:/Users/HP/OneDrive/Desktop/New.txt","C:/Users/HP/OneDrive/Desktop/ss.txt")

print("The File has been successfully renamed!")

Output:

The File has been successfully renamed!

File after updating the name —

Python Rename File
Python Rename File

Here, we have updated/renamed a file to ss.txt using rename() function.


Conclusion

By this, we have come to the end of this topic. Please feel free to comment below, in case you come across any doubt.

For more such articles related to Python, do visit Python@AskPython.


References

  • Python Rename Directory — JournalDev