Python : How to check if a directory is empty ?

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.

os.listdir(path='.')

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

'''
    Check if a Directory is empty : Method 1
'''    
if len(os.listdir('/home/varun/temp') ) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")

If given folder is empty then it will print,

Directory is empty

Check if a directory is empty : Method 2

'''
    Check if a Directory is empty : Method 2
'''    
if not os.listdir('/home/varun/temp') :
    print("Directory is empty")
else:    
    print("Directory is not empty")        

If given folder is empty then it will print,

Directory is empty

 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()

dirName = '/home/varun/temp';

'''
    Check if a Directory is empty and also check exceptional situations.
'''    
if os.path.exists(dirName) and os.path.isdir(dirName):
    if not os.listdir(dirName):
        print("Directory is empty")
    else:    
        print("Directory is not empty")
else:
    print("Given Directory don't exists")

Complete example is as follows,

import os

def main():
    
    dirName = '/home/varun/temp';
    
    '''
        Check if a Directory is empty and also check exceptional situations.
    '''    
    if os.path.exists(dirName) and os.path.isdir(dirName):
        if not os.listdir(dirName):
            print("Directory is empty")
        else:    
            print("Directory is not empty")
    else:
        print("Given Directory don't exists")        
        

    '''
        Check if a Directory is empty : Method 1
    '''    
    if len(os.listdir('/home/varun/temp') ) == 0:
        print("Directory is empty")
    else:    
        print("Directory is not empty")
        

    '''
        Check if a Directory is empty : Method 2
    '''    
    if not os.listdir('/home/varun/temp') :
        print("Directory is empty")
    else:    
        print("Directory is not empty")        
 

    print ("****************")
    
if __name__ == '__main__':
    main()

Output:

Directory is empty
Directory is empty
Directory is empty

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top