Finding empty directories

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):
    for entry in os.listdir(dir):
            if isfile(join(dir,entry))==True:
                isEmpty = False
                subEmpty =  walksub(join(dir, entry))
                if subEmpty==True:
                    subDirs.append(join(dir, entry))
        except :
            print ("error checking: "+entry)
    if isEmpty == False:
        for subDir in subDirs:
            print subDir
    return isEmpty


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

comments powered by Disqus