rename multiple files in python

How to Rename Multiple Files in Python

Often you may need to rename multiple files in folder or directory. While it is easy to do this in Linux, if you are using Windows system, it can be quite tedious to do this. Luckily, you can use a scripting language like python to easily rename multiple files in directory. In this article, we will learn how to rename multiple files in directory with Python.


How to Rename Multiple Files in Python

We will use os.listdir() and os.rename() functions to list files in a directory, and rename them respectively. Here are the syntaxes of both these functions.

os.listdir('folder_path')

In the above example, you need to mention the folder path to your directory in listdir() function. It will return a list of filenames.

os.rename(source, destination)

os.rename() function takes two arguments – source address of the file to be renamed & destination address of new filename. You can use this function any file extension, not just text files.

Here is a simple code that loops through the list of all files in the folder mentioned in os.listdir() function and renames each of them one by one.

# importing os module
import os
 
# Function to rename multiple files
def main():
   
    folder = "/home/ubuntu/data"
    for count, filename in enumerate(os.listdir(folder)):
        dst = f"New File {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
    main()

In the above code, we first import os module and then define main() function. In this function, we define the folder path which contains files to be renamed.

We call listdir() function on this folder which returns a list of filenames. Then we loop through the list to construct source and destination names of each file which needs to be renamed. We also specify the folder name along with filename so that it works even if your python script is in a separate folder than the files to be renamed. In each iteration, we call rename() function to rename the file.

Finally, we add a driver code to ensure that this function when it is called from within python script only, and not when it is imported elsewhere.

In this article, we have learnt how to bulk rename multiple files in python. You can always use mv and find commands if you are on Linux but python script is useful if you want to do the renaming from within your application/website.

Also read:

Python Script to Load Data in MySQL
NGINX Pass Headers from Proxy Server
How to Populate MySQL Table With Random Data
How to Get Query Execution Time in MySQL
How to Get File Size in Python

Leave a Reply

Your email address will not be published.