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:
srcis a string that specifies the source filedstis a string that specifies the source file
note
- If the
srcfile does not exist, theos.rename()function raises aFileNotFounderror. - If the
dstalready exists, theos.rename()function issues aFileExistsErrorerror.
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)