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 filedst
is a string that specifies the source file
note
- If the
src
file does not exist, theos.rename()
function raises aFileNotFound
error. - If the
dst
already exists, theos.rename()
function issues aFileExistsError
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)