Finding empty directories
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?"



on 17 January 2010 at 07:03 Mark Mc Mahon said …
Hi, Even though I love python - there is another way
pushd your_dir
for /D /R %d in (*) do rd /q %d
popd
the /D tells the FOR to find only directories
The /R tells the FOR to search recursively
Because /s isn't supplied to RD it will only remove empty directories.
on 17 January 2010 at 08:53 J.B. Nicholson-Owens said …
In Unix "find . -type d -empty -print" with GNU find finds and lists empty directories (replace the dot with the directory you want to start from if you don't want to start from the present working directory).
This might be more useful to pipe to other programs if you change "-print" into "-print0" and use xargs to process each directory. Or perhaps you want to count the empty directories: append "|wc -l" to get a count.
I don't use Windows much and when I do I tend to use Cygwin. Therefore Unix commands are cross-platform for me (and they scale up very well). I suppose one could mount an SMB fileshare with Samba and use a Unix machine scan those directories from a Unix machine.
on 17 January 2010 at 08:53 J.B. Nicholson-Owens said …
By the way, the "Preview" button seems to be a post button.
on 18 January 2010 at 17:27 PN said …
Wrap your if isfile(join(dir,entry))....... block of code
in a try/except continue block to avoid access denied errors killing your script mid processing on Windows.
on 19 January 2010 at 03:53 Kerim Mansour said …
@PN: I didn't have any problems but your right anyway. Changed the code