Last modified: Feb 06, 2026 By Alexander Williams

Python Rename File: A Complete Guide

Renaming files is a common task. Python makes it simple. You can automate file management with just a few lines of code. This guide will show you how.

We will cover two main methods. The first uses the os module. The second uses the modern pathlib module. Both are powerful and easy to learn.

Why Rename Files Programmatically?

Manually renaming files is slow. It is also prone to errors. Python scripts can rename hundreds of files in seconds. This is useful for organizing photos, documents, or data.

You can use renaming in batch jobs. For example, adding dates to log files. Or standardizing names for a project. Automation saves time and ensures consistency.

Prerequisites for Renaming Files

You need Python installed. Any recent version (3.6+) will work. You also need basic knowledge of How to Run Python File in Terminal.

You should understand file paths. Know the difference between absolute and relative paths. This is key to avoiding errors.

Method 1: Using the os.rename() Function

The os module is a classic tool. It provides the os.rename() function. This function takes two arguments: the source and the destination.

The source is the current file name. The destination is the new file name. Both must be strings representing the file path.

Basic os.rename() Example

Let's rename a single file. We will change "old_report.txt" to "new_report.txt". First, ensure the file exists in your script's directory.


import os

# Define the original and new file names
src = "old_report.txt"
dst = "new_report.txt"

# Rename the file
os.rename(src, dst)
print(f"File renamed from {src} to {dst}")

File renamed from old_report.txt to new_report.txt

Handling Errors with os.rename()

What if the file doesn't exist? The script will crash with a FileNotFoundError. We must handle this. Use a try-except block.

Also, check if the destination file already exists. On most systems, os.rename() will overwrite it. This can cause data loss.


import os

src = "missing_file.txt"
dst = "renamed_file.txt"

try:
    os.rename(src, dst)
    print("Rename successful!")
except FileNotFoundError:
    print(f"Error: The file '{src}' was not found.")
except FileExistsError:
    print(f"Error: The file '{dst}' already exists.")

Error: The file 'missing_file.txt' was not found.

Method 2: Using the pathlib Module (Modern Approach)

Python 3.4 introduced pathlib. It offers an object-oriented way to handle paths. The Path.rename() method is clean and readable.

Pathlib is now the recommended way. It makes your code easier to understand and maintain across different operating systems.

Basic pathlib Rename Example

We will perform the same rename operation. First, create a Path object for the source file. Then call its rename() method.


from pathlib import Path

# Create Path objects
src_path = Path("old_report.txt")
dst_path = Path("new_report.txt")

# Rename the file
src_path.rename(dst_path)
print(f"File renamed to {dst_path}")

Why Pathlib is Often Better

Pathlib handles paths as objects. You can easily join paths with the `/` operator. It also provides methods to check if a file exists.

This can make your rename logic safer and more explicit. Let's see an example with checks.


from pathlib import Path

src_path = Path("data.txt")
dst_path = Path("archive_data.txt")

if src_path.exists():
    if not dst_path.exists():
        src_path.rename(dst_path)
        print("File safely renamed.")
    else:
        print("Destination file already exists. Aborting.")
else:
    print("Source file not found.")

Renaming Multiple Files (Batch Renaming)

This is where Python shines. You can loop through files in a directory. Then rename each one based on a pattern.

Use os.listdir() or Path.iterdir() to get file lists. Always test your pattern on a sample first.

Example: Adding a Prefix to Files

Let's add "backup_" to all .txt files in a folder. We'll use pathlib for this task.


from pathlib import Path

# Define the directory
directory = Path("./documents")

# Loop through all .txt files in the directory
for file_path in directory.glob("*.txt"):
    # Create the new name
    new_name = "backup_" + file_path.name
    new_path = file_path.parent / new_name
    # Rename the file
    file_path.rename(new_path)
    print(f"Renamed {file_path.name} to {new_name}")

Renamed report1.txt to backup_report1.txt
Renamed notes.txt to backup_notes.txt

Important Considerations and Best Practices

Renaming files is a powerful but risky operation. A small mistake can overwrite important data. Follow these tips.

1. Check File Existence

Always check if the source file exists. Also, decide what should happen if the destination exists. Should you skip, overwrite, or create a new name?

2. Use Absolute Paths for Clarity

Relative paths depend on the current working directory. This can change. Using absolute paths makes your script's behavior more predictable.

3. Test with Print Statements First

Before running the actual rename, do a "dry run". Print the old and new names. This lets you verify the logic without changing any files.

This simple step can prevent many headaches. It's a crucial part of How to Run Python File in Terminal safely.

4. Handle Cross-Platform Differences

File systems differ. Windows, Linux, and macOS have unique rules. Pathlib helps here. It automatically handles path separators (\\ vs /).

Be mindful of case sensitivity. Linux is case-sensitive; Windows is often not. Your script should account for this if it will run on multiple systems.

Common Errors and How to Fix Them

Beginners often encounter a few specific errors. Knowing them in advance will help you debug faster.

PermissionError: [Errno 13] Permission denied

This happens if the file is open in another program. Or if your script doesn't have write permissions. Close the file in other apps. Run your script as an administrator if needed.

FileNotFoundError: [Errno 2] No such file or directory

The source path is wrong. Double-check the file name and path. Use Path.exists() or os.path.exists() to verify.

IsADirectoryError / NotADirectoryError

You are trying to rename a directory as a file, or vice versa. Ensure your source and destination types match.

Conclusion

Renaming files in Python is straightforward. The os.rename() function is reliable. The pathlib module offers a modern, robust approach.

Start with simple renames. Always include error handling. Test your scripts thoroughly before using them on important files.

With this knowledge, you can automate tedious file organization tasks. You can build powerful tools to manage your data efficiently. Remember to practice safe file operations by checking paths and testing first.