How to rename a directory or file in Python :
Renaming of a directory or file is always required if you are dealing with the filesystem. Note that the filesystem works differently on different platforms. Even if you are developing applications for mobile platforms (Android or iOS), it will be different.
In this tutorial, we will learn how to_ rename a directory or a 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 :
os.rename(src,dst)
Where, 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 looks like as below :
Explanation :
The commented numbers in the above program denote the step numbers below :
-
We are importing the os module and path at the start of the program. As mentioned before, we need to import the os module as the ‘rename’ method is available inside this module.
-
file_path is the default folder path where the sample file is stored. Change the value of this variable with the file path on your system.
Note that this is the folder path where the file exists, not the complete file path.
- src is the_ source file name_ stored in the above folder. You need to change the value of this variable as well.
dst is the file name we need after the rename.
- 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.
This step is necessary because if the file doesn’t exist or if our file path is not correct, the program will throw an error. So, for a large application, the above safety check will simply print the message instead of crashing the whole program.
After you run this program, your filename should be changed to modifiedFile.txt.
Practical use :
“Where I am going to use it ?” - this is the first question that might come to your mind.
This program has a lot of use cases. I have used it for renaming a large set of a file with one go. For example, if you want to remove any special characters from all music file names in your system, you can write one program to do that. Or if you want to add your name to the end of thousands of files, you can do it similarly.
Python is really good for automation and it makes repetitive tasks much easier. You can use any other programming language to do the same, but I prefer to use python.
Try to run the program using Python 3 and if you have any other use cases in your mind, drop a comment below.