Rename Multiple File with Python

How to Rename Multiple Files in a Directory Using Python

Renaming multiple files in a directory can be a tedious task if done manually. However, with Python, we can automate this process with just a few lines of code. In this tutorial, we will explore how to rename multiple files in a directory using Python’s os and glob modules.

Why Automate File Renaming?

There are several reasons why you might want to rename multiple files at once:

  • Standardizing file names for consistency (e.g., appending a prefix or suffix).
  • Renaming based on file extensions or attributes.
  • Organizing files for easier management.

Let’s dive into how we can achieve this using Python.

Prerequisites

Before we begin, make sure you have Python installed on your system. You can check your Python version by running the following command in your terminal:

python --version

If you haven’t installed Python yet, you can download it from the official Python website.

Step-by-Step Guide to Renaming Files in Python

Step 1: Import Required Modules

We will use the os module to interact with the file system and the glob module to find specific files in a directory.

import os
import glob
  • os: This module provides functions for interacting with the operating system, such as renaming files.
  • glob: This module is useful for finding files with specific patterns (e.g., all .txt files in a directory).

Step 2: Define the Directory and File Pattern

You need to specify the directory where your files are located and the pattern to match the files you want to rename.

directory = '/path/to/your/directory'
file_pattern = '*.txt'  # This matches all .txt files in the directory

In this example, we’re looking to rename all .txt files in the directory. You can modify the file_pattern based on your needs (e.g., *.jpg for images or *_* for files with underscores).

Step 3: Loop Through Files and Rename

We will loop through all the files that match our pattern and rename them based on a new naming convention. Here’s an example of renaming files by adding a prefix:

for filepath in glob.glob(os.path.join(directory, file_pattern)):
    filename = os.path.basename(filepath)  # Get the file name
    new_filename = f"new_{filename}"  # Add prefix 'new_'
    new_filepath = os.path.join(directory, new_filename)

    # Rename the file
    os.rename(filepath, new_filepath)
    print(f'Renamed: {filename} to {new_filename}')

Explanation:

  1. glob.glob(): Retrieves all files matching the file_pattern in the specified directory.
  2. os.path.basename(): Extracts the file name from the full file path.
  3. os.rename(): Renames the file by moving it from the old name to the new one.

In this example, every .txt file will be renamed by adding the prefix new_. For example, file1.txt will become new_file1.txt.

Step 4: Custom Renaming Logic

You can modify the renaming logic to suit your needs. For instance, you might want to rename files based on numbers or timestamps.

Here are a few examples:

Example 1: Rename Files with an Incremental Number
count = 1
for filepath in glob.glob(os.path.join(directory, file_pattern)):
    extension = os.path.splitext(filepath)[1]  # Get the file extension
    new_filename = f'file_{count}{extension}'  # Rename as file_1.txt, file_2.txt, etc.
    new_filepath = os.path.join(directory, new_filename)

    os.rename(filepath, new_filepath)
    print(f'Renamed: {os.path.basename(filepath)} to {new_filename}')
    count += 1
Example 2: Rename Files by Replacing a Word

If you want to rename files by replacing a specific word in the file names:

old_word = 'old'
new_word = 'new'
for filepath in glob.glob(os.path.join(directory, file_pattern)):
    filename = os.path.basename(filepath)
    new_filename = filename.replace(old_word, new_word)  # Replace 'old' with 'new'
    new_filepath = os.path.join(directory, new_filename)

    os.rename(filepath, new_filepath)
    print(f'Renamed: {filename} to {new_filename}')

This code will find all files containing the word old and replace it with new in the file name.

Step 5: Run the Script

Once you’ve finalized your renaming logic, save the Python script and run it. For example:

python rename_files.py

Make sure the script is in the same environment where Python is installed.

Important Notes

  1. Backup your files: Before running a renaming script, it’s always a good idea to back up your files to avoid unintended loss or overwriting.
  2. Test with a few files: Start by testing the script with a few files to make sure it behaves as expected.
  3. Be cautious with file paths: Make sure you’re targeting the correct directory and files to avoid accidental renaming in unintended locations.

Conclusion

Renaming multiple files in a directory using Python is a powerful way to save time and effort. By leveraging the os and glob modules, you can create custom scripts to rename files in bulk based on various patterns and criteria.

With a little modification, the examples provided can be adapted to fit a wide range of use cases. Whether you’re organizing project files or cleaning up downloaded files, this method can be a valuable tool in your automation arsenal.

Happy coding!