Python | os.removedirs() method
Last Updated :
29 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.removedirs()
method in Python is used to remove directories recursively. If the leaf directory in the specified path is successfully removed, then os.removedirs()
tries to successively remove every parent directory mentioned in path until an error is raised. The raised error is ignored because generally error is raised because directory to be deleted is not empty.
For example consider the following path:
'/home/User/Documents/foo/bar/baz'
In above path, os.removedirs()
method will try to remove the leaf directory first i.e ‘baz’. If the leaf directory ‘baz’ is successfully removed then method will try to remove ‘/home/User/Documents/foo/bar’ then ‘/home/User/Documents/foo/’ then ‘/home/User/Documents’ until an error is raised. The directory to be deleted should be empty.
Syntax: os.removedirs(path)
Parameter:
path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
Return Type: This method does not return any value.
Code #1: Use of os.removedirs() method to remove an empty directory tree
import os
directory = "baz"
parent = "/home/User/Documents/foo/bar"
path = os.path.join(parent, directory)
os.removedirs(path)
print ( "Directory '%s' has been removed successfully" % directory)
|
Output:
Directory 'baz' has been removed successfully
Code #2: Possible errors while using os.removedirs() method
import os
path = '/home/User/Documents/ihritik/file.txt'
os.removedirs(path)
|
Output:
Traceback (most recent call last):
File "removedirs.py", line 33, in
os.removedirs(path)
File "/usr/lib/python3.6/os.py", line 238, in removedirs
rmdir(name)
NotADirectoryError: [Errno 20] Not a directory: '/home/User/Documents/ihritik/file.txt'
Code #3: Handling errors while using os.removedirs() method
import os
path = '/home/User/Documents/ihritik/file.txt'
try :
os.removedirs(path)
print ( "Director removed successfully" )
except NotADirectoryError:
print ( "Specified path is not a directory." )
except PermissionError:
print ( "Permission denied." )
except OSError as error:
print (error)
print ( "Directory can not be removed" )
|
Output:
Specified path is not a directory.
Reference: https://docs.python.org/3/library/os.html
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...