How to rename a file using Python

23    Asked by PhilWilson in Python , Asked on May 11, 2025

How can you rename a file using Python? Learn which built-in modules and simple commands allow you to easily change a file's name programmatically, whether you're automating tasks or organizing files.

Answered by Zora Heidenreich

Renaming a file in Python is quick and easy using the built-in os module. This is especially helpful when automating file management tasks, like renaming logs, images, or downloaded files.

1. Using os.rename():

The most straightforward way is with the os.rename() function:

import os
os.rename("old_filename.txt", "new_filename.txt")

  • This renames old_filename.txt to new_filename.txt.
  • If the file doesn’t exist or the new name already exists, it will throw an error.

2. Handling Errors Gracefully:

To avoid crashes, wrap the rename in a try-except block:

try:
    os.rename("old.txt", "new.txt")
    print("File renamed successfully.")
except FileNotFoundError:
    print("The file does not exist.")
except FileExistsError:
    print("A file with the new name already exists.")
except Exception as e:
    print(f"An error occurred: {e}")

3. Using pathlib (Python 3.4+):

For a more modern approach:

from pathlib import Path
Path("old_file.txt").rename("new_file.txt")

pathlib is more readable and works well with paths in a cross-platform way.

A Few Tips:

  • Make sure you have the correct permissions to modify the file.
  • Always double-check your file paths, especially when working with directories.

Renaming files with Python is a simple task, but it becomes incredibly powerful when used in bulk operations or file automation scripts.



Your Answer

Interviews

Parent Categories