In this tutorial, we will learn how to rename a directory or file in python with 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 :
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 the os module. For that reason, we need to import os at the start of the program.
The final python program will look like as below :
#1 import os from os import path #2 file_path = 'C:\Sample\' #3 src = 'originalFile.txt' dst = 'modifiedFile.txt' #4 if path.exists(file_path + src): os.rename(file_path+src, file_path+dst) else: print("The input file doesn't exist")
This program is available [here](https://github.com/codevscolor/codevscolor/blob/master/python/renamefiledirectory.py) on Github.
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.
- filepath_ is the default folder path where the sample file is stored.
- src is the source file name stored in the above folder. 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.
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.
- Python tutorial to remove duplicate lines from a text file
- Python program to count the total number of lines in a file
- Python program to rename a directory or file
- Python program to delete all files with specific extension in a folder
- Python program to remove special characters from all files in a folder
- How to sort all files in a folder in Python