The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Using Python to Rename Multiple Files

Renaming multiple files manually can be time-consuming and error-prone, especially when dealing with large volumes of files. Python offers a powerful and flexible way to automate this process using built-in libraries such as os and glob. Whether you need to add prefixes, replace specific text, or change file extensions, Python can streamline batch renaming tasks efficiently.

Understanding File Renaming Basics in Python

To begin renaming files using Python, it’s essential to understand how the os module interacts with the file system. This module allows developers to navigate directories, retrieve file lists, and rename files.

Here’s a simple example of renaming a single file:

python
import os old_name = "oldfile.txt" new_name = "newfile.txt" os.rename(old_name, new_name)

The os.rename() function takes two parameters: the current file name and the new file name. If the file exists and the names are valid, Python will rename it without any additional prompts.

Batch Renaming with os and glob

For renaming multiple files, you can use a loop combined with the glob module, which helps in pattern matching file names.

Example: Adding a Prefix to Files

Assume you have multiple .txt files and want to add the prefix “backup_”.

python
import os import glob files = glob.glob("*.txt") for filename in files: new_name = "backup_" + filename os.rename(filename, new_name)

This script fetches all .txt files in the current directory, then renames each one by adding “backup_” as a prefix.

Renaming Files with Sequential Numbers

You may want to rename files in a sequence like image_1.jpg, image_2.jpg, and so on. Here’s how you can achieve that:

python
import os import glob files = glob.glob("*.jpg") for index, filename in enumerate(files, start=1): new_name = f"image_{index}.jpg" os.rename(filename, new_name)

Using enumerate() ensures that each file receives a unique index. The f-string format provides clean and readable syntax.

Replacing Text in File Names

If you need to replace specific substrings in file names, Python can do this easily using string methods.

python
import os for filename in os.listdir('.'): if "draft" in filename: new_name = filename.replace("draft", "final") os.rename(filename, new_name)

This script scans the current directory, identifies files containing the word “draft”, and replaces it with “final”.

Changing File Extensions

Another common renaming task is changing file extensions, such as converting .jpeg files to .jpg.

python
import os for filename in os.listdir('.'): if filename.endswith(".jpeg"): new_name = filename.replace(".jpeg", ".jpg") os.rename(filename, new_name)

This solution targets only files ending in .jpeg, preserving the integrity of other file types.

Renaming Files in Nested Directories

When dealing with subfolders, you can use os.walk() to traverse directories recursively.

python
import os for root, dirs, files in os.walk('.'): for filename in files: if filename.endswith(".txt"): old_path = os.path.join(root, filename) new_path = os.path.join(root, "renamed_" + filename) os.rename(old_path, new_path)

This example walks through every subdirectory and renames .txt files by adding the “renamed_” prefix.

Handling Errors During Renaming

It’s a good practice to include error handling, especially when working with file systems, to prevent data loss or unexpected behavior.

python
import os try: os.rename("file1.txt", "file2.txt") except FileNotFoundError: print("File not found.") except PermissionError: print("Permission denied.") except Exception as e: print(f"Error occurred: {e}")

By wrapping os.rename() in a try-except block, you can manage exceptions gracefully and debug issues more effectively.

Using pathlib for Object-Oriented File Handling

Python 3.4+ introduced the pathlib module, which offers a more object-oriented approach to file manipulation.

python
from pathlib import Path path = Path(".") for file in path.glob("*.txt"): new_name = file.with_name("renamed_" + file.name) file.rename(new_name)

Pathlib simplifies path operations and makes the code more intuitive and readable, particularly when working across platforms.

Renaming Based on File Metadata

In some cases, you might want to rename files based on metadata such as creation date or file size.

python
import os from datetime import datetime for filename in os.listdir('.'): if filename.endswith(".log"): creation_time = os.path.getctime(filename) date_str = datetime.fromtimestamp(creation_time).strftime('%Y-%m-%d') new_name = f"log_{date_str}.log" os.rename(filename, new_name)

This script renames .log files by appending the creation date, providing an organized and chronological naming scheme.

Case Conversion in File Names

Python can also help in standardizing case in file names, such as converting all names to lowercase:

python
import os for filename in os.listdir('.'): new_name = filename.lower() os.rename(filename, new_name)

Or changing to uppercase:

python
import os for filename in os.listdir('.'): new_name = filename.upper() os.rename(filename, new_name)

Sorting Files Before Renaming

Sometimes, the renaming logic may depend on sorting the files. You can use sorted() for this:

python
import os import glob files = sorted(glob.glob("*.png")) for index, filename in enumerate(files, 1): new_name = f"frame_{index:03}.png" os.rename(filename, new_name)

The :03 in the format string ensures that numbers are padded with zeros (e.g., frame_001.png), which is useful for maintaining proper order in filenames.

Conclusion

Python’s flexibility and simplicity make it an ideal tool for batch renaming files. From adding prefixes and changing extensions to renaming based on metadata, Python scripts can be customized for virtually any use case. Using libraries like os, glob, and pathlib, developers and administrators can automate tedious file management tasks, reduce human error, and improve productivity. With minimal effort, Python enables scalable and consistent file renaming solutions suitable for personal, academic, or enterprise environments.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About