In this article we will discuss different ways to check if a directory is empty or not.

Python’s os module provides a function to get the list of files or folder in a directory i.e.

It returns a list of all the files and sub directories in the given path.

Now if the returned list is empty or it’s size is 0 then it means directory is empty.

Check if a directory is empty : Method 1

If given folder is empty then it will print,

Check if a directory is empty : Method 2

If given folder is empty then it will print,

 Check if a directory is empty in exceptional scenarios

There can be scenarios when os.listdir() can throw exception. For example,

  • If given path don’t exist
  • If Given path exists but its not a Directory

In both the cases os.listdir() will throw error, so we need to check this first before calling os.lisdir()

Complete example is as follows,

Output:

 

Python Recommendations:

C++ & C++11 Recommendations:

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.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.