Rename File in Python

Python – Rename File

To rename file in Python, import os library, call os.rename() function, and pass the old file path and new file path as arguments.

The syntax to call os.rename() function to rename a file is

import os

os.rename('source', 'destination')

The path to the file should also be included in the file name.

Example

In the following program, we will rename the file “sample_1.txt” to “sample_2.txt”.

Source File

Python - Rename File

Python Program

import os

old_file_name = "myfolder/sample_1.txt"
new_file_name = "myfolder/sample_2.txt"

try :
	os.rename(old_file_name, new_file_name)
	print('File renamed successfully.')
except:
	print('Could not rename file.')
	print('An exception occurred.')
Copy

Output

File renamed successfully.

Renamed File

Python - Rename File

Summary

In this tutorial of Python Examples, we learned how to rename a file using os.rename() function, with the help of examples.

Code copied to clipboard successfully 👍