Rename multiple files in python

In this session, we are going to learn how to change the name of multiple files of a given directory.

How to rename multiple files of a given directory in python

There is an OS module in python which provides rename ()  method to rename the files or directory.
and also another method is listdir()  which  lists out all the contents of a given directory. in the list dir method, we have to pass the source address. and in the rename method, we have to pass both source method as well as the destination as a paramere.

The basic syntax for os.rename() method:

os.rename(sourse,destination):

The basic syntax for os.listdir() method:

l=os.listdir(sourse):

Now I am going to show you the program:
1st import the os module:

#import os module for using rename method and listdir
import os

Create a method  and some variable which handles all the operations:

#method which handle all the operation regarding rename the file.
def rename_files():
    #variable initialization
    i=0

Take a loop which helps to travel the files:

#loop to travel all the file of given folder ravi.
for file_name in os.listdir("ravi"):
    #new name of  the file should be like newname1.html...
    dstination="newname" + str(i) + ".html"
    sourse='ravi'+ file_name
    dstination='ravi'+ dstination

Now I am going to take the rename method to rename the file name:

#rename function calls to rename the files.
       os.rename(sourse, dstination)
       #variable increment to differenciate the all files like newname1.html
       #,newname2.html ..... so on.
       i += 1

Now combine the whole program :

#import os module for using rename method and listdir
import os
#method which handle all the operation regarding rename the file.
def rename_files():
    #variable initialization
    i=0
    #loop to travel all the file of given folder ravi.
    for file_name in os.listdir("ravi"):
        #new name of  the file should be like newname1.html...
        dstination="newname" + str(i) + ".html"
        sourse='ravi'+ file_name
        dstination='ravi'+ dstination
        #rename function calls to rename the files.
        os.rename(sourse, dstination)
        #variable increment to differenciate the all files like newname1.html
        #,newname2.html ..... so on.
        i += 1
    print("All files has been renamed successfully...")    
#rename_files method call.
rename_files()

Output:

All files has been renamed successfully...

 

Leave a Reply

Your email address will not be published. Required fields are marked *