Python os.removedirs() Method
os.removedirs() Overview
The os.removedirs() method is used to recursively remove directories.
Like rmdir(), if the subfolders are successfully removed, removedirs() tries their parent until an error is thrown (which is largely ignored because it generally means your folder is not empty).
os.removedirs() Syntax
The syntax format of the removedirs() method is as follows.
os.removedirs(path)
os.removedirs() Parameters
- path – the path to the directory to be removed
os.removedirs() Return Value
This method has no return value.
os.removedirs() Example#1
The following example demonstrates the use of the removedirs() method.
#!/usr/bin/python3
import os, sys
# list categories
print ("The directory is (by os.listdir): %s" %os.listdir(os.getcwd()))
# remove
os.removedirs("/root/aaa/bbb")
# List removed directories
print ("The directory after removal is :" %os.listdir(os.getcwd()))
Output:
os.removedirs() Example#2
Possible errors while using os.removedirs() method.
-
If the specified path is not a directory then
NotADirectoryError
exception will be raised. -
If the specified path is not an empty directory then an
OSError
will be raised. -
If there is any permission issue while removing the directory then the
PermissionError
exception will be raised. -
similarly if specified path is invalid an
OSError
will be raised.
import os
# Path
path = '/root/apidemos.com.txt'
# Remove the specified path
os.removedirs(path)
Output: