Python os.rmdir() Method.
os.rmdir() Overview
The os.rmdir() method is used to delete a directory at the specified path. Only if this folder is empty, otherwise, OSError is thrown.
os.rmdir() Syntax
The syntax format of the rmdir() method is as follows.
os.rmdir(path)
os.rmdir() Parameters
- path – the path to the directory to be deleted
os.rmdir() Return Value
This method has no return value.
os.rmdir() Example#1
The following example demonstrates the use of the rmdir() method.
#!/usr/bin/python3
import os, sys
# List Directory
print ("The directory is : %s"%os.listdir(os.getcwd()))
# Delete path
os.rmdir("ccc")
# List the renamed directories
print ("The directory is : %s" %os.listdir(os.getcwd()))
Output:
os.rmdir() Example#2
Handling errors while using os.rmdir() method.
-
if the specified path is not an empty directory then permission error will be raised.
-
similarly if specified path is invalid or is not a directory then corresponding OSError will be raised.
import os
# Directory name
directory = "bbb"
parent = "/root/aaa-apidemos"
# Path
path = os.path.join(parent, directory)
# Remove the Directory "bbb"
try:
os.rmdir(path)
print("Directory '%s' has been removed successfully" %directory)
except OSError as error:
print(error)
print("Directory '%s' can not be removed" %directory)
Output: