How to rename a directory or file in Python :
In this tutorial, we will learn how to rename a directory or file in python with an example.
Python has one built-in method called rename that can be used for renaming a file or directory. This method is defined as below :
src: It is the source file name or source directory name. This parameter should be valid.
dst : This is the new destination name, i.e. new file name or directory name.
One thing you have seen that we are using the os module here, or the rename function is available inside os module. For that reason, we need to import os at the start of the program.
Example program :
The final python program will look like as below :
The commented numbers in the above program denote the step numbers below :
1. We are importing the os module and path at the start of the program.
2. file_path is the default folder path where the sample file is stored.
3. src is the source file name stored in the above folder. dst is the file name we need after the rename.
4. Using the exists() method, we are checking if the file actually exists or not. If it doesn’t exist, we are printing one error message. Else, we are renaming the file using the os.rename() method as explained above.
After you run this program, your filename should be changed to modifiedFile.txt.
Try to run the program and drop one comment below if you have any question.
You might also like :
- Python File operations
- List all the files in a Zip file using Python 3
- Python program to count the number of words in a file
- Python 3 program to count the number of blank spaces in a file
- Python tutorial to remove duplicate lines from a text file
- Python program to count the total number of lines in a file