Check if a directory is empty or not in Python

Hi guys, today we will be going to learn how to check if a directory is empty or not in Python. So what is this directory? A directory is basically an organizational unit used to organize folders and files into hierarchical structures.

We can check if a directory is empty or not in Python using different functions listed below:

  1. os.path.exists()
  2. os.listdir()

So let’s continue reading this article to check out each one with examples…

Using exists() method of the os.path module

We can use os.path which is a submodule of the os module in Python. The os.path consists of exists() method which can be used to check if the directory is empty or not. The os.path.exists(path) method returns True if path refers to an existing path else returns False.
Implementation:

import os.path 
path1 ='C:/Users/sachin verma/file.txt'
isdir1 = os.path.isdir(path1) 
if(isdir1):
    print("Not empty directory")
else:
    print("empty directory") 
    
path2 ='C:/Users/sachin verma/'
isdir2 = os.path.isdir(path2) 
if(isdir2):
    print("Not empty directory")
else:
    print("Empty directory")

Output:

Empty directory
Not empty directory

Using listdir() method of the os module

The os module consists of listdir() method which returns the list of all the files and directories in the specified directory.If the list is empty then the directory is empty. For instance, see the code below.

import os 
path ='C:/Users/sachin verma/' 
directory= os.listdir(path) 
if len(directory) == 0: 
    print("Empty directory") 
else: 
    print("Not empty directory")

Output

Not empty directory

Thus to conclude we can say that we can use the os and the os.path module to check whether the given directory is empty or not.

One response to “Check if a directory is empty or not in Python”

  1. Shrish Kumar says:

    The first method won’t work.

    os.path.isdir() checks for existence of directory not for being empty. It will print ‘Not empty directory’ even for empty.

Leave a Reply