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:

 

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