How to check if fol...
 
Share:
Notifications
Clear all

How to check if folder is empty with Python?


myTechMint
(@mytechmint)
Member Moderator
Joined: 4 years ago
Posts: 52
Topic starter  

I am trying to check if a folder is empty and do the following:

import os
downloadsFolder = '../../Downloads/'
if not os.listdir(downloadsFolder):
print "empty"
else:
print "not empty"

Unfortunately, I always get "not empty" no matter if I have any files in that folder or not. Is it because there might be some hidden system files? Is there a way to modify the above code to check just for not hidden files?


Quote
Topic Tags
myTechMint
(@mytechmint)
Member Moderator
Joined: 4 years ago
Posts: 52
Topic starter  

You can use these two methods from the os module.

The First option:

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

 

The 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")

 


ReplyQuote