How to rename multiple files recursively using Python?

PythonServer Side ProgrammingProgramming

You can use os.walk to recursively walk through the directory and subsequently use os.rename to rename the files.


import os
def replace(folder_path, old, new):
    for path, subdirs, files in os.walk(folder_path):
        for name in files:
            if(old.lower() in name.lower()):
                file_path = os.path.join(path,name)
                new_name = os.path.join(path,name.lower().replace(old,new))
                os.rename(file_path, new_name)

You can use this function as follows −

replace('my_folder', 'IMG', 'Image')

This will find all files recursively within the folder and its sub-folders and replace IMG with Image in each one of them. You can modify the function as it suits you for a better result suited to your need.

Published on 26-Dec-2017 10:33:15