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.
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
import os os.chdir(r"C:/Users/HP/OneDrive/Desktop/") os.rename("Programming","PRACTICE") print("The Directory has been successfully renamed!")
os.chdir() function is used to change the current working directory.
The Directory has been successfully renamed!
Directory after updating the name:
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.
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!")
The File has been successfully renamed!
File after updating the name —
Here, we have updated/renamed a file to ss.txt using rename() function.
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 [email protected].
- Python Rename Directory — JournalDev