Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Rename multiple files using Python

  • Difficulty Level : Easy
  • Last Updated : 22 Nov, 2021

Prerequisite: OS module in Python
In Python3, rename() method is used to rename a file or directory. This method is a part of the os module and comes in extremely handy. 

Syntax for os.rename() :

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

os.rename(src, dst) : src is source address of file to be renamed and dst is destination with the new name.

Now say given n images in a folder having random names. For example, consider the image below:

Now the requirement is to rename them in ordered fashion like hostel1, hostel2, …and so on. Doing this manually would be a tedious task but this target can be achieved using the rename() and listdir() methods in the os module.

The listdir method lists out all the content of a given directory.

Syntax for listdir() : 

list = os.listdir(‘src’) : where src is the source folder to be listed out.

The following code will do the job for us. It traverses through the lists of all the images in xyz folder, defines the destination (dst) and source (src) addresses, and renames using rename module. 

The accepted format for destination (dst) and source (src) addresses to be given as arguments in os.rename(src,dst) is “folder_name/file_name”.
Below is the implementation : 


# Pythono3 code to rename multiple
# files in a directory or folder
# importing os module
import os
# Function to rename multiple files
def main():
    folder = "xyz"
    for count, filename in enumerate(os.listdir(folder)):
        dst = f"Hostel {str(count)}.jpg"
        src =f"{folder}/{filename}"  # foldername/filename, if .py file is outside folder
        dst =f"{folder}/{dst}"
        # rename() function will
        # rename all the files
        os.rename(src, dst)
# Driver Code
if __name__ == '__main__':
    # Calling main() function

Output :
The output of this code will look something like this – 

Note : This code may not run in online IDE, since it use external image file directory.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!