In this article we will discuss how to get list of all empty directories.

Python’s os module provides a function to iterate over a directory tree i.e.

It iterates of the directory tree at give path and for each directory or sub directory it returns a tuple containing,
(<Dir Name> , <List of Sub Dirs> , <List of Files>.

Now let’s use this to create a list of empty directories in a directory tree.

Creating a list of all empty Directories in a directory tree

  • Create a list to Store empty directories
  • Now Traverse all the files in given path using os.walk() :
    • For each Directory, check if it has no files and sub directories. If yes then add its path in the list.

Creating a list of all empty Directories in a directory tree using List Comprehension

More pythonic approach is a single line solution using List Comprehension,

Complete example is as follows,

Output:

 

 

 

Python Resources

C++11 / C++14 Resources

Design Patterns Resources

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,