os.removedirs() method in Python

In this article, we will be looking at the os.removedirs() method in Python of the OS module. Or we can say, how to remove empty directories of a path recursively in Python. Firstly, the OS module consists of functions to exploit the operating system operations. Secondly, the OS module generates OSError for any wrong file names or unreachable path to the file. It also handles any unsupported arguments passed onto the module functions. The os.removedirs() method in Python is one such method to handle file manipulations. Deleting a file in python follows a similar process.

It is a method to remove empty directories of a path recursively until an exception is raised or all the empty directories are deleted for the specified path.

os.removedirs() method recursively delete the leaf directories and move on to its immediate parent directory to continue the deletion.

Implementation of os.removedirs() in Python

NOTE:- the method raises an error for a file and does not delete files.

for example, consider the following path:- D:\sample\Test\1\2\3\4\5\6\7\8\9 

os.removedirs() method in Python

The sample folder consists of two directories, Test and Test1. Therefore, while deleting the empty directories, our deletion should stop when Test1 is left in the sample directory.

the command first deletes directory 9 as it is empty.

Now when we execute the following code, it deletes all the empty directories including its empty parent directories until a non-empty directory.

import os #it contains the os module functions
path=r"D:\sample\Test\1\2\3\4\5\6\7\8\9"
os.removedirs(path)

Output:-

remove empty directories of a path recursively

This deletes all the empty directories.

I hope you liked the article, feel free to post queries below.

Leave a Reply

Your email address will not be published. Required fields are marked *