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:
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.
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.
Directory 'baz' has been removed successfully
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'
Specified path is not a directory.
- class method vs static method in Python
- Python | os.dup() method
- Python | set() method
- Python | next() method
- Python | os.setgroups() method
- Python | iter() method
- Python | os.open() method
- Python | setattr() method
- Python | os.ftruncate() method
- Python | os.WIFEXITED() method
- Python | Decimal max() method
- Python | sympy.apart() method
- Python | os.waitid() method
- Python | sympy.Mod() method
- Python | Decimal min() method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.