Python program to rename a file or directory

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 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 the 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 :

#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.

Explanation :

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. filepath_ 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.

python rename file directory

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.

Similar tutorials :

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️