Deleteing empty directories

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Mar 30 17:38:54 CEST 2009


On Mon, 30 Mar 2009 08:14:55 -0700, CinnamonDonkey wrote:

> My understanding was that rmtree removes a whole tree not just the empty
> directories?


So it seems:

>>> os.mkdir('die-die-die')
>>> os.mkdir('die-die-die/stuff')
>>> shutil.rmtree('die-die-die')
>>>                                  

I think what you want is os.removedirs().

>>> os.makedirs('root/die-die-die/empty/empty/empty')
>>> os.listdir('root')
['keep', 'die-die-die']
>>> os.removedirs('root/die-die-die/empty/empty/empty')
>>> os.listdir('root')
['keep']




> def isDirEmpty( path ):
>     if not os.path.isdir( path ):
>         return False
> 
>     contents = os.listdir( path )
> 
>     if len(contents) == 0:
>         return True
> 
>     return False

That can be simplified to:

# untested
def isDirEmpty(path):
    return os.path.isdir(path) and not len(os.listdir(path))



> def RecurseTree( path ):
>     if not os.path.isdir( path ):
>         return False

What if it is a symbolic link to a directory?

>     contents = os.listdir( path )
>
>     if len(contents) == 0:
>         print "Deleting Empty Dir '%s'" % (path,) #shutil.rmtree(path)

Why do you go to the trouble of defining isDirEmpty() and then not use it?

>     else:
>         for item in contents:
>             investigate = "%s\\%s" % (path, item) if
>             os.path.isdir(investigate):
>                 RecurseTree( investigate )

As soon as you start recursively walking over directories, you should use 
os.walk. It will almost certainly do what you want.


> if __name__ == '__main__':
>     RecurseTree( r"c:\temp" )
> 
> 
> But I'm not sure what the max recursion depth is in python?

By default in my version:

>>> sys.getrecursionlimit()
1000

but it can be changed.


> Plus I think this could be more efficient.

Probably, but why do you care? The file I/O probably will take 99% of the 
time, and I doubt you can improve that.

Of course I could be wrong, so profile, profile, profile, and find out 
where the time really is being spent.


-- 
Steven



More information about the Python-list mailing list