Python os.rename() Method
os.rename() Overview
The os.rename() method is used to name a file or directory from src to dst, throwing OSError if dst is an existing directory.
os.rename() Syntax
The syntax format of the rename() method is as follows.
os.rename(src, dst)
os.rename() Parameters
- src – the name of the directory to be modified
- dst – the name of the directory to be modified
os.rename() Return Value
This method has no return value.
os.rename() Example#1
The following example demonstrates the use of the rename() method.
#!/usr/bin/python3
import os, sys
# List Directory
print ("The directory is : %s"%os.listdir(os.getcwd()))
# Rename
os.rename("aaa","aaa-apidemos")
print ("Rename successfully.")
#
print ("List the renamed directories: %s" %os.listdir(os.getcwd()))
Output:
os.rename() Example#2
Handling possible errors.
-
If Source is a file but destination is a directory will raise
IsADirectoryError
error. -
If source is a directory but destination is a file will raise
NotADirectoryError
error.
import os
# Source file path
source = '/root/apidemos.com.txt'
# destination file path
dest = '/root/aaa-apidemos'
try :
os.rename(source, dest)
print("Source path renamed to destination path successfully.")
except IsADirectoryError:
print("Source is a file but destination is a directory.")
except NotADirectoryError:
print("Source is a directory but destination is a file.")
# For permission related errors
except PermissionError:
print("Operation not permitted.")
# For other errors
except OSError as error:
print(error)
Output: