Skip to main content

Python Rename File

The os Python module provides a big range of useful methods to manipulate files and directories.

The os.rename() method is used to rename a file.

Syntax

The syntax of os.rename() is:

os.rename(src, dst)

where:

  • src is a string that specifies the source file
  • dst is a string that specifies the source file
note
  • If the src file does not exist, the os.rename() function raises a FileNotFound error.
  • If the dst already exists, the os.rename() function issues a FileExistsError error.

Example: Rename File

For example, rename the file old_file.txt to new_file.txt.

import os

os.rename('old_file.txt', 'new_file.txt')

Example: Rename File with Handling Exceptions

You can use the try...except statement to avoid an error if the file to rename doesn't exist or if the new filename already exists.

A safe way to rename the file old_file.txt to new_file.txt is as follows:

import os

try:
os.rename('old_file.txt', 'new_file.txt')
except FileNotFoundError as e:
print(e)
except FileExistsError as e:
print(e)