5 Best Ways to Rename Multiple Files Using Python

πŸ’‘ Problem Formulation: In the realm of file management, a common task is to bulk rename files. For instance, you might want to rename a batch of images from ‘pic1.jpg’, ‘pic2.jpg’, … to ‘holiday1.jpg’, ‘holiday2.jpg’, … Python provides various methods to automate this process, saving time and reducing the potential for error. This article presents five effective methods for renaming multiple files using Python, ranging from basic looping to advanced one-liners.

Method 1: Using os.rename()

Rename operations in Python can be straightforwardly accomplished using the os.rename() function. This method iterates over files in a directory and renames each file using two arguments: the current file name and the new file name. It’s part of the standard library and doesn’t require additional modules.

Here’s an example:

import os

def rename_files(directory, old_prefix, new_prefix):
    for filename in os.listdir(directory):
        if filename.startswith(old_prefix):
            new_name = filename.replace(old_prefix, new_prefix)
            os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))

rename_files('path_to_directory', 'pic', 'holiday')

Output:

‘pic1.jpg’, ‘pic2.jpg’, … are renamed to ‘holiday1.jpg’, ‘holiday2.jpg’, …

This code snippet defines a function rename_files that takes a directory path and two prefixes as parameters. It loops through each file in the specified directory, checks if it starts with the old prefix, replaces it with the new prefix, and then renames the file accordingly.

Method 2: Using pathlib

The pathlib module, introduced in Python 3.4, represents filesystem paths as objects with relevant methods and attributes. Its Path.rename() method is an object-oriented approach for file renaming and can simplify both the code and the process.

Here’s an example:

from pathlib import Path

def rename_files(path, old_suffix, new_suffix):
    folder = Path(path)
    for file in folder.glob('*' + old_suffix):
        file.rename(Path(folder, file.name.replace(old_suffix, new_suffix)))

rename_files('path_to_directory', '.txt', '.md')

Output:

‘document1.txt’, ‘note2.txt’, … are renamed to ‘document1.md’, ‘note2.md’, …

In this script, rename_files leverages the pathlib module to rename all files with a given suffix in a specified directory. The Path.glob() method is used to filter files by the old suffix and Path.rename() method for the actual renaming.

Method 3: Using glob and os.rename()

Combining glob.glob(), which returns a list of filenames matching a specified pattern, with os.rename(), allows for pattern-specific file renaming. This can be particularly useful when dealing with files of a certain type or naming scheme.

Here’s an example:

import os
import glob

def rename_files(directory, pattern, replacement):
    for filepath in glob.glob(os.path.join(directory, pattern)):
        new_file = filepath.replace(pattern, replacement)
        os.rename(filepath, new_file)

rename_files('path_to_directory', 'report*.pdf', 'summary')

Output:

‘report01.pdf’, ‘report02.pdf’, … are renamed to ‘summary01.pdf’, ‘summary02.pdf’, …

This function, rename_files, uses the glob module to find all files matching the ‘report*.pdf’ pattern in the specified directory and then renames them by replacing the word ‘report’ with ‘summary’ before the numeric part of the filename.

Method 4: Using os.scandir() and os.rename()

The os.scandir() function, which returns an iterator of directory entries along with file attribute information, can be used for more efficient file traversal and renaming. This method is especially advantageous when dealing with a large number of files.

Here’s an example:

import os

def rename_files(directory, search_str, replace_str):
    with os.scandir(directory) as entries:
        for entry in entries:
            if entry.is_file() and search_str in entry.name:
                new_name = entry.name.replace(search_str, replace_str)
                os.rename(entry.path, os.path.join(directory, new_name))

rename_files('path_to_directory', 'IMG_', 'Image_')

Output:

‘IMG_001.png’, ‘IMG_002.png’, … are renamed to ‘Image_001.png’, ‘Image_002.png’, …

The rename_files function uses os.scandir() to create an iterator over directory entries. It filters for files containing a specified string and renames them with the os.rename() method.

Bonus One-Liner Method 5: Using a list comprehension

Python’s list comprehension can be used for concise, one-line file renaming operations. Although compact, this method is powerful and can be used for simple renaming patterns.

Here’s an example:

import os

[os.rename(f, f.replace('session', 'workshop')) for f in os.listdir('path_to_directory') if f.startswith('session')]

Output:

‘session1.mp4’, ‘session2.mp4’, … are renamed to ‘workshop1.mp4’, ‘workshop2.mp4’, …

This single line of code utilizes a list comprehension to iterate over files in a directory, check if they start with ‘session’, and rename them to start with ‘workshop’ instead using os.rename().

Summary/Discussion

  • Method 1: os.rename(). Convenient with the standard library. Limited to simple rename operations. Can’t handle more complex patterns or filtering without additional logic.
  • Method 2: pathlib. Modern, object-oriented, and readable. Works well with more complex file paths. Limited to Python 3.4 and later.
  • Method 3: glob and os.rename(). Useful for pattern matching. Ideal for file types or naming conventions. Requires understanding of glob patterns.
  • Method 4: os.scandir() and os.rename(). Efficient for large directories. Yields more file attributes. More verbose than other methods.
  • Method 5: List Comprehension. Quick and concise one-liner. Lacks clarity for complex operations. Not as readable for beginners.