The Wayback Machine - https://web.archive.org/web/20240628070448/https://www.geeksforgeeks.org/python-os-removedirs-method/
Open In App

Python | os.removedirs() method

Last Updated : 29 May, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python program to explain os.removedirs() method 
    
# importing os module 
import os
  
# Leaf Directory name
directory = "baz"
  
# Parent Directory
parent = "/home/User/Documents/foo/bar"
  
# Path
path = os.path.join(parent, directory)
  
# Remove the Directory
# "baz"
os.removedirs(path)
print("Directory '%s' has been removed successfully" %directory)
  
# All parent directory
# of 'baz' will be also
# removed if they are empty
  


Output:

Directory 'baz' has been removed successfully
Code #2: Possible errors while using os.removedirs() method




# Python program to explain os.removedirs() method 
    
# importing os module 
import os
  
  
# 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
  
# Path
path = '/home/User/Documents/ihritik/file.txt'
  
# Try to remove
# the specified path
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




# Python program to explain os.removedirs() method 
    
# importing os module 
import os
  
# Path
path = '/home/User/Documents/ihritik/file.txt'
  
# Try to remove
# the specified path
  
try:
    os.removedirs(path)
    print("Director removed successfully")
  
# If path is not a directory
except NotADirectoryError:
    print("Specified path is not a directory.")
  
# If permission related errors
except PermissionError:
    print("Permission denied.")
  
# for other errors
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



Previous Article
Next Article

Similar Reads

Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
4 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Python Dictionary get() Method
Python Dictionary get() Method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument). Python Dictionary get() Method Syntax: Syntax : Dict.get(key, default=None) Parameters: key: The key name of the item you want to return the value fromValue: (Optional) Value to
2 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() method
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. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() method
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. os.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg