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:

 

 

 

Click Here to Subscribe for more Articles / Tutorials like this.