close

How to check if folder is empty with Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to check if folder is empty with Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to check if folder is empty with Python?

  1. How to check if folder is empty with Python?

    However, the os.listdir() can throw an exception, for example when the given path does not exist. Therefore, you need to cover this.

  2. check if folder is empty with Python

    However, the os.listdir() can throw an exception, for example when the given path does not exist. Therefore, you need to cover this.

Method 1

You can use these two methods from the os module.

First option:

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")

Second option (as an empty list evaluates to False in Python):

import os
if not os.listdir('/your/path'):
    print("Directory is empty")
else:    
    print("Directory is not empty")

However, the os.listdir() can throw an exception, for example when the given path does not exist. Therefore, you need to cover this.

import os
dir_name = '/your/path'
if os.path.isdir(dir_name):
    if not os.listdir(dir_name):
        print("Directory is empty")
    else:    
        print("Directory is not empty")
else:
    print("Given directory doesn't exist")

I hope it will be helpful for you.

Method 2

Since Python 3.5+,

if any(os.scandir(path)):
   print('not empty')

which generally performs faster than listdir() since scandir() is an iterator and does not use certain functions to get stats on a given file.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read