How to rename multiple files recursively using Python?


The act of renaming multiple files recursively in Python can be a useful task when it is required to change the names of multiple files within a directory and its subdirectories. If you need to replace certain characters, add prefixes or suffixes, or completely change the file names, Python has powerful tools to accomplish such operations. In this article, we explore a few different approaches to renaming multiple files recursively using Python. We consider some code examples, each demonstrating a unique method to achieve this task. So let us get started right away and learn how to rename multiple files recursively with ease.

Making Use of os.walk() to Traverse the Directory Tree

The os.walk() function from os module is used to traverse the directory tree and access files and directories within it. We utilize this function to iterate over all the files in a directory and its subdirectories and perform the renaming operation. Let us consider an example that shows how to use os.walk() to rename multiple files recursively:

Example

  • We start by defining a function called rename_files_recursively that takes three parameters: directory, old_name, and new_name. These parameters indicate the directory path, the old name of the files to be renamed, and the new name that will replace the old name.

  • Within the function, we make use of the os.walk() function to iterate over all the files and directories in the given directory and its subdirectories. The function outputs three values for each iteration: the root directory, a list of directories, and a list of files.

  • We then iterate over the files list and check if the old_name is present in the file name.

  • If the old_name is found, we generate the full path of the file using os.path.join(root, file). We also create the new file path by replacing the old_name with the new_name using the replace() method.

  • Finally, we use the os.rename() function to rename the file by moving it from the original path to the new path.

  • This method permits us to recursively traverse the directory tree and rename all the matching files found within the specified directory and its subdirectories.

import os

def rename_files_recursively(directory, old_name, new_name):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if old_name in file:
                file_path = os.path.join(root, file)
                new_file_path = os.path.join(root, 
file.replace(old_name, new_name))
                os.rename(file_path, new_file_path)

# Example usage
rename_files_recursively('/path/to/directory', 
'old_name', 'new_name')

Making Use of pathlib.Path.glob() Method to Find Files

Another way to rename multiple files recursively is by using the glob() method from the pathlib module. The glob() method allows us to find files based on a specific pattern or criteria. By using it along with the rglob() method, which performs a recursive search, we can easily locate and rename multiple files. Here's an example that demonstrates this approach:

Example

  • We, firstly, define a function called rename_files_recursively that takes the same parameters as in the previous method: directory, `old_name, and new_name`.

  • Inside the function, we create a Path object using the declared directory path.

  • We then use the rglob('*') method to recursively iterate over all the files and directories within the specified directory and its subdirectories.

  • For each file_path found, we check if it is a file (file_path.is_file()) and if the old_name is present in the file name.

  • If the conditions are fulfilled, we construct the new file path by replacing the old_name with the new_name using the replace() method and the with_name() method of the Path object.

  • Lastly, we rename the file by using the rename() method of the Path object, passing in the new file path.

This method offers a compact and efficient way to locate and rename multiple files recursively using the glob() and rglob() methods from the pathlib module.

from pathlib import Path

def rename_files_recursively(directory, old_name, new_name):
    path = Path(directory)
    for file_path in path.rglob('*'):
        if file_path.is_file() and old_name in file_path.name:
            new_file_path = 
file_path.with_name(file_path.name.replace(old_name, new_name))
            file_path.rename(new_file_path)

# Example usage
rename_files_recursively('/path/to/directory', 
'old_name', 'new_name')

Example

Here, a function rename_files_recursively is defined that takes two parameters: folder_path which is the path of the folder where the files are located, and new_prefix which is the new prefix to be added to the filenames. The function utilizes the os.walk() method to navigate through the folder and its subdirectories recursively. It then renames each file by appending the new prefix to its original name using the os.rename() function.

import os

def rename_files_recursively(folder_path, new_prefix):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            file_dir, file_name = os.path.split(file_path)
            new_name = new_prefix + file_name
            new_path = os.path.join(file_dir, new_name)
            os.rename(file_path, new_path)

# Usage
rename_files_recursively('/path/to/folder', 'new_prefix_')

Example

In this code, we have a function rename_files_recursively that accepts three parameters: folder_path is the path of the folder where the files are located, search_string is the string to be replaced in the filenames, and replace_string is the string to replace the search string. The function works through the folder and its subdirectories, and for each file, it checks if the search string exists in the filename. If it does, it replaces the search string with the replace string using the replace() method and renames the file using os.rename().

import os

def rename_files_recursively(folder_path, search_string, 
replace_string):
   for root, dirs, files in os.walk(folder_path):
      for file in files:
         if search_string in file:
            file_path = os.path.join(root, file)
            new_name = file.replace(search_string, 
replace_string)
            new_path = os.path.join(root, new_name)
            os.rename(file_path, new_path)

# Usage
rename_files_recursively('/path/to/folder', 'old_string', 'new_string')

In this article, we have explored some different strategies for renaming multiple files recursively using Python. By using the os.walk() function and the glob() and rglob() methods from the pathlib module, we can easily traverse the directory tree, locate the desired files, and rename them based on specific criteria. In one example you add a new prefix to each filename, while in another example we perform a search and replace operation on the filenames. Both examples utilize the power of Python's os module to interact with the file system and efficiently rename files in a recursive manner.

In case you need to perform bulk renaming tasks or modify file names to adhere to a specific naming convention, Python offers a wide range of powerful tools to accomplish these tasks efficiently. With the knowledge gained from this article, you can confidently manipulate file names and organize your files effectively in your Python projects.

Updated on: 25-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements