Skip to content

Python Rename File with os.rename()

How to rename files in Python using the os.rename() function, including handling common errors like missing source files or duplicate destinations.

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

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)
Navigation