python

How to check if a directory is empty in Python

In this tutorial, we are going to see different ways to check if a directory is empty or not.

The “os” module of Python provides listdir() function to get the list of files or folders in a directory, It returns a list of all the files and subdirectories of the given path. So if the returned list is empty or if its size is 0, it means that the directory is empty.
 

 

How to check if a directory is empty in Python
import os

if len(os.listdir('/home/user/doc')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")

If the given folder is empty, it produces the following output:

Directory is empty

 
os.listdir() may throw an exception. For example,

  • If the given path does not exist
  • If the given path exists but it is not a directory

In both cases, os.listdir() will display an error. So we have to check this before calling os.listdir().

import os

dir = '/home/user/doc'

if os.path.isdir(dir) and os.path.exists(dir):
    if len(os.listdir('/home/user/doc')) == 0:
        print("Directory is empty")
    else:    
        print("Directory is not empty")
else:
    print("Directory does not exist")
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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