Skip to content Skip to sidebar Skip to footer

How To Check If Folder Is Empty With Python?

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

Solution 1:

You can use these two methods from the os module.

First option:

import osiflen(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 osifnotos.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'ifos.path.isdir(dir_name):
    ifnotos.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.

Solution 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.

Solution 3:

Hmm, I just tried your code changing the path to an empty directory and it did print "empty" for me, so there must be hidden files in your downloads. You could try looping through all files and checking if they start with '.' or not.

EDIT:

Try this. It worked for me.

if [f for f inos.listdir(downloadsFolder) ifnot f.startswith('.')] == []:
    print"empty"else: 
    print"not empty"

Solution 4:

Give a try to:

import os
dirContents = os.listdir(downloadsFolder)
ifnot dirContents:
    print('Folder is Empty')
else:
    print('Folder is Not Empty')

Solution 5:

As mentioned by muskaya here. You can also use pathlib. However, if you only want to check, if the folder is empty or not, you should check out this answser:

from pathlib import Path

defdirectory_is_empty(directory: str) -> bool:
    returnnotany(Path(directory).iterdir())


downloadsFolder = '../../Downloads/'if directory_is_empty(downloadsFolder):
    print"empty"else:
    print"not empty"

Post a Comment for "How To Check If Folder Is Empty With Python?"