Posted by: sureshamrita | July 5, 2009

Recursively removing empty directories using python


#!/usr/bin/python
import os
from os.path import join
def remEmptyDir(mypath):
for root, dirs, files in os.walk(mypath,topdown=False):
     for name in dirs:
         fname = join(root,name)
         if not os.listdir(fname): #to check wither the dir is empty
             print fname
             os.removedirs(fname)

remEmptyDir('/home/suresh/photos')


Responses

  1. it does delete only bottom dirs. you’re left with bunch of directories containing other empty dirs.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Categories

%d bloggers like this: