Rename a File using Python

In Python, you can rename a file using the os.rename() function from the built-in os module. This function takes two arguments: the current file name and the new file name, allowing you to rename files efficiently.


Examples to Rename a File

1. Renaming a File in the Same Directory

In this example, we rename an existing file in the same directory using the os.rename() function. We shall rename example.txt to renamed_file.txt.

main.py

</>
Copy
import os

# Specify the current file name and new file name
old_name = "example.txt"
new_name = "renamed_file.txt"

# Rename the file
os.rename(old_name, new_name)

print(f"File renamed from '{old_name}' to '{new_name}'")

Explanation:

  1. Import the os module, which provides functions for interacting with the operating system.
  2. Define the old_name variable as the current name of the file ("example.txt").
  3. Define the new_name variable as the new name we want to assign to the file ("renamed_file.txt").
  4. Use os.rename(old_name, new_name) to rename the file.
  5. Print a message confirming that the file has been renamed.

Output:

File renamed from 'example.txt' to 'renamed_file.txt'

2. Checking if a File Exists Before Renaming

In this example, we check whether the file exists before renaming it to avoid errors.

main.py

</>
Copy
import os

# Define file names
old_name = "document.txt"
new_name = "updated_document.txt"

# Check if the file exists before renaming
if os.path.exists(old_name):
    os.rename(old_name, new_name)
    print(f"File renamed to '{new_name}'")
else:
    print(f"Error: '{old_name}' does not exist")

Explanation:

  1. Import the os module.
  2. Define old_name as the current file name ("document.txt").
  3. Define new_name as the new file name ("updated_document.txt").
  4. Use os.path.exists(old_name) to check if the file exists.
  5. If the file exists, rename it using os.rename(); otherwise, print an error message.

Output:

File renamed to 'updated_document.txt'

3. Renaming a File in a Different Directory

In this example, we rename a file that is stored in a different directory.

We shall provide complete or absolute path of both file names: old and new; to the rename() method.

main.py

</>
Copy
import os

# Define file paths
old_path = "C:/Users/tutorialkart/Documents/sample.txt"
new_path = "C:/Users/tutorialkart/Documents/renamed_sample.txt"

# Rename the file
os.rename(old_path, new_path)

print(f"File renamed to '{new_path}'")

Explanation:

  1. Import the os module.
  2. Define old_path as the full path to the file.
  3. Define new_path as the new full path with the new file name.
  4. Use os.rename(old_path, new_path) to rename the file.
  5. Print a success message.

Output:

File renamed to 'C:/Users/John/Documents/renamed_sample.txt'

4. Handling Errors While Renaming a File

In this example, we handle errors that may occur while renaming a file, such as permission issues or file not found errors.

main.py

</>
Copy
import os

# Define file names
old_name = "notes.txt"
new_name = "archived_notes.txt"

try:
    os.rename(old_name, new_name)
    print(f"File renamed to '{new_name}'")
except FileNotFoundError:
    print(f"Error: '{old_name}' not found")
except PermissionError:
    print(f"Error: Permission denied when renaming '{old_name}'")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Explanation:

  1. Import the os module.
  2. Define the old_name and new_name.
  3. Use a try-except block to handle potential errors.
  4. Catch FileNotFoundError if the file does not exist.
  5. Catch PermissionError if renaming is not allowed due to system permissions.
  6. Catch any other unexpected errors using Exception.

Output:

File renamed to 'archived_notes.txt'

Conclusion

Renaming a file in Python is simple using the os.rename() function. To avoid errors, check if the file exists before renaming it and handle potential exceptions. This ensures smooth file operations in your Python scripts.