All the subfolders have the same folders with same names. I want to check which subfolders named dbound are empty in all the directories inside a main folder as in the example.
About half of the folders with that name are empty. How to find out which? I tried this:
from glob import glob
for i in glob(r'C:\Users\user\Desktop\files1' + '**/*/*/*', recursive=True):
print (i)
if os.listdir(i) == []:
print ("Empty")
glob
can return directories and files. Check if entry is a directory before testing it. And to test the name use os.path.basename
if os.path.basename(i) == "dbound" and os.path.isdir(i) and not os.listdir(i):
print ("{} is Empty".format(i))
I would prefer os.walk
(at least directories are filtered out, and files are ignored):
for root,dirs,files in os.walk(r'C:\Users\user\Desktop\files1'):
for d in dirs:
if d=="dbound" and not os.listdir(os.path.join(root,d)):
print("empty dbound: {}".format(os.path.join(root,d)))
Both solutions work, but somehow are unsatisfactory because you're scanning the disk twice (glob
/os.walk
and os.listdir
)
To avoid scanning twice, you'd have to store the result in dictionary/defaultdict and count the files in each dir, filter the ones with no file in it. More complex. Do it only if disk performance matters.