How to Rename Files in Python?

As a developer, while working on a project I came across a situation where I needed to organize a large collection of files and change the name of a single file, Python provides a simple way to accomplish this task. We’ll explore various methods, from the simplest to more advanced techniques. In this tutorial, I will explain how to rename files in Python with suitable examples.

Rename Files in Python

Imagine you have a folder filled with hundreds of files named after US states, such as “california.txt”, “texas.txt”, and “florida.txt”. Your task is to rename each file to include the state’s capital, like “sacramento_california.txt”, “austin_texas.txt”, and “tallahassee_florida.txt”. Doing this manually would be incredibly time-consuming and prone to errors.

Read How to Check if a File is Empty in Python?

Solution: Use os Module

Python’s built-in os module provides a simple and effective way to rename files. The os.rename() function allows you to change the name of a file or directory in your Python program. Here’s a basic example:

import os

os.rename('california.txt', 'sacramento_california.txt')

I executed the above example and added the screenshot below.

Rename Files in Python

In this code snippet, we import the os module and use the os.rename() function to change the name of the file from “california.txt” to “sacramento_california.txt”.

Check out How to Get File Name Without Extension in Python?

Hande File Paths

When working with files in different directories, you need to specify the complete file path. Here’s an example:

import os

old_name = '/path/to/folder/texas.txt'
new_name = '/path/to/folder/austin_texas.txt'
os.rename(old_name, new_name)

I executed the above example and added the screenshot below.

How to Rename Files in Python

Make sure to replace /path/to/folder/ with the actual path to your file.

Read How to Write Multiple Lines to a File in Python?

Rename Multiple Files

To rename multiple files, you can use a loop to iterate over the files in a directory. Here’s an example that renames all “.txt” files in a folder to include the state capital:

import os

folder_path = '/path/to/folder/'
for filename in os.listdir(folder_path):
    if filename.endswith('.txt'):
        state = filename[:-4]  # Remove '.txt' extension
        capital = get_state_capital(state)  # Function to get state capital
        new_filename = f"{capital}_{state}.txt"
        old_path = os.path.join(folder_path, filename)
        new_path = os.path.join(folder_path, new_filename)
        os.rename(old_path, new_path)

In this example, we use os.listdir() to get a list of all files in the specified folder_path. We then iterate over each file, check if it has a “.txt” extension, and extract the state name from the filename. The get_state_capital() function (not shown here) would return the corresponding state capital. Finally, we construct the new filename and use os.rename() to rename the file.

Read How to Write Lines to a File in Python?

Handle Errors and Exceptions

When renaming files, it’s important to handle potential errors and exceptions gracefully. For example, if the destination file already exists, os.rename() will raise a FileExistsError. You can catch and handle this exception using a try-except block:

import os

try:
    os.rename('florida.txt', 'tallahassee_florida.txt')
except FileExistsError:
    print("Destination file already exists!")

In this case, if “tallahassee_florida.txt” already exists, the program will print an error message instead of raising an exception.

Check out How to Clear a File in Python?

Best Practices and Tips

Here are some best practices and tips to keep in mind when renaming files with Python:

  1. Always check if the source file exists before attempting to rename it. You can use os.path.exists() for this purpose.
  2. Be cautious when renaming files in a loop. Make sure your loop conditions and file paths are correct to avoid unintended changes.
  3. Use meaningful and descriptive names for your files to improve organization and searchability.
  4. If you need to rename files based on a specific pattern or criteria, consider using regular expressions with the re module in Python.

Read How to Read XML Files in Python?

Conclusion

Renaming files using Python is a powerful and efficient way to organize and manage your files. By leveraging the os module and following best practices, you can easily rename single files or batch rename multiple files at once. With this knowledge, you can save time and effort in your file management tasks.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.