Python 3 – os.removedirs() Method
In Python, the os.removedirs() method lets you remove multiple directories that are empty. It is useful when you need to remove a directory and all its subdirectories in one go. The os.removedirs() method works by removing each directory in the path argument, and if any directory fails to be removed, it aborts the operation, and an error is thrown.
Syntax
os.removedirs(path)
Parameters
The os.removedirs() method has one parameter:
path
: This is a string representing the directory path to be removed.
Return Value
The os.removedirs() method has no return value. If it completes successfully, the directory and all its subdirectories are removed. If it fails, an error is thrown.
Example
To demonstrate how the os.removedirs() method works, consider the following code:
import os
path = 'C:/MyFolder/MySubfolder'
try:
os.removedirs(path)
print('Directory', path, 'was removed.')
except:
print('Directory', path, 'was not removed.')
In this example, the os.removedirs() method is used to try to delete the directory ‘C:/MyFolder/MySubfolder’. If the directory is successfully removed, the text ‘Directory C:/MyFolder/MySubfolder was removed.’ is printed to the console. If an error occurs, the text ‘Directory C:/MyFolder/MySubfolder was not removed.’ is printed to the console.
Error Handling
The os.removedirs() method may raise the following errors:
OSError
: This error is raised when the directory path specified does not exist or when it is not empty.-
NotADirectoryError
: This error is raised when the path argument is not a directory. -
FileNotFoundError
: This error is raised when the path argument does not exist.
Conclusion
In this article, we have discussed the os.removedirs() method in Python 3. We have seen the syntax, parameters, return value, and examples of how to use this method. We also covered how to handle errors when working with os.removedirs(). We hope this article has been helpful to you in understanding the os.removedirs() method in Python 3.