Finding empty directories

Last Update: 17.01.2010. By kerim in python | snipplet

I know it sounds trivial but as usual the trivial things are those that are most annoying. Running through the harddrive of my notebook i came accross way to much garbage manifesting itself through empty directories.

After some 30 minutes of “search and despair” i simply decided to stop clicking.

Here is a result of that after 5 minutes. Never underestimate the batteries:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('c:\\'):
    if len(dirs)==0 and len(files)==0:
        print root

The results gave me the creeps. You only get the empty directories at the lowest level. So here is a better version:

import os
from os.path import join, isfile

def walksub(dir):
    isEmpty=True
    subDirs=[]
    for entry in os.listdir(dir):
        try:
            if isfile(join(dir,entry))==True:
                isEmpty = False
            else:
                subEmpty =  walksub(join(dir, entry))
                if subEmpty==True:
                    subDirs.append(join(dir, entry))
                else:
                    isEmpty=False
        except :
            print ("error checking: "+entry)
            isEmpty=False
    if isEmpty == False:
        for subDir in subDirs:
            print subDir
    return isEmpty


walksub('c:\\')

Now here is the 1 million dollar question: “What are all those empty directories good for?”