How to rename a file using Python

Learn how to rename a file using python with practical examples, diagrams, and best practices. Covers python, file-rename development techniques with visual explanations.

How to Rename Files in Python: A Comprehensive Guide

Hero image for How to rename a file using Python

Learn various methods to rename files and directories in Python, covering basic renaming, moving, and handling potential errors.

Renaming files is a common operation in many programming tasks, from organizing data to preparing files for specific applications. Python provides straightforward ways to achieve this using its built-in modules. This article will guide you through the essential methods for renaming files and directories, including handling different scenarios and potential issues.

Basic File Renaming with os.rename()

The most fundamental way to rename a file or directory in Python is by using the os.rename() function from the os module. This function takes two arguments: the original path of the file/directory and the new path. If the new path specifies a different directory, os.rename() effectively moves the file.

import os

# Create a dummy file for demonstration
with open("old_name.txt", "w") as f:
    f.write("This is a test file.")

try:
    os.rename("old_name.txt", "new_name.txt")
    print("File renamed successfully from old_name.txt to new_name.txt")
except FileNotFoundError:
    print("Error: The original file was not found.")
except OSError as e:
    print(f"Error renaming file: {e}")

# Clean up (optional)
# os.remove("new_name.txt")

Renaming a file using os.rename()

Renaming and Moving Files to a Different Directory

As mentioned, os.rename() can also be used to move a file to a different directory while optionally changing its name. This is achieved by providing a new path that includes the target directory. The target directory must already exist; os.rename() will not create it.

import os

# Create a dummy file and a target directory
if not os.path.exists("temp_dir"):
    os.makedirs("temp_dir")

with open("original_file.txt", "w") as f:
    f.write("Content to be moved.")

try:
    os.rename("original_file.txt", os.path.join("temp_dir", "moved_file.txt"))
    print("File moved and renamed successfully.")
except FileNotFoundError:
    print("Error: The original file was not found.")
except OSError as e:
    print(f"Error moving/renaming file: {e}")

# Clean up (optional)
# os.remove(os.path.join("temp_dir", "moved_file.txt"))
# os.rmdir("temp_dir")

Moving and renaming a file to a different directory

flowchart TD
    A[Start]
    A --> B{File Exists?}
    B -->|No| C[Error: File Not Found]
    B -->|Yes| D{New Path Exists?}
    D -->|Yes| E[Overwrite Existing File]
    D -->|No| F[Rename/Move File]
    F --> G[End]
    E --> G

Flowchart of the os.rename() operation

Handling Renaming with shutil.move()

For more robust file operations, especially when dealing with moving files across different file systems or ensuring directory creation, the shutil module is often preferred. The shutil.move() function can move a file or directory from one location to another. If the destination is a directory, the source is moved inside it. If the destination is a file, the source is renamed to it.

import os
import shutil

# Create a dummy file and a target directory
if not os.path.exists("destination_folder"):
    os.makedirs("destination_folder")

with open("source_file.txt", "w") as f:
    f.write("This file will be moved by shutil.")

try:
    # Move and rename the file
    shutil.move("source_file.txt", os.path.join("destination_folder", "renamed_and_moved.txt"))
    print("File moved and renamed using shutil.move() successfully.")
except FileNotFoundError:
    print("Error: The source file was not found.")
except shutil.Error as e:
    print(f"Error moving file with shutil: {e}")

# Clean up (optional)
# os.remove(os.path.join("destination_folder", "renamed_and_moved.txt"))
# os.rmdir("destination_folder")

Using shutil.move() to move and rename a file

Renaming Multiple Files (Batch Renaming)

Often, you'll need to rename multiple files based on a pattern or a sequence. This can be achieved by iterating through files in a directory and applying a renaming logic. The os.listdir() function is useful for getting a list of all items in a directory.

import os

# Create some dummy files for batch renaming
if not os.path.exists("batch_rename_dir"):
    os.makedirs("batch_rename_dir")

for i in range(1, 4):
    with open(os.path.join("batch_rename_dir", f"image_{i}.jpg"), "w") as f:
        f.write(f"Content for image {i}")

print("Files before renaming:")
for filename in os.listdir("batch_rename_dir"):
    print(filename)

# Batch rename logic
for filename in os.listdir("batch_rename_dir"):
    if filename.startswith("image_") and filename.endswith(".jpg"):
        old_path = os.path.join("batch_rename_dir", filename)
        new_filename = filename.replace("image_", "photo_")
        new_path = os.path.join("batch_rename_dir", new_filename)
        try:
            os.rename(old_path, new_path)
            print(f"Renamed {filename} to {new_filename}")
        except OSError as e:
            print(f"Error renaming {filename}: {e}")

print("\nFiles after renaming:")
for filename in os.listdir("batch_rename_dir"):
    print(filename)

# Clean up (optional)
# for filename in os.listdir("batch_rename_dir"):
#     os.remove(os.path.join("batch_rename_dir", filename))
# os.rmdir("batch_rename_dir")

Batch renaming files in a directory