Deleteing empty directories

Tim Golden mail at
Mon Mar 30 16:59:54 CEST 2009

CinnamonDonkey wrote:
> Hi All,
> I've been scratching my head all afternoon trying to work out the best/
> quickest way is to delete empty directories within a tree (Windows).
> I've looked at os.walk() but it seems to traverse the directory tree
> in the wrong order (is it possible to reverse the order?)
> It seems the only way is to manually walk the tree myself recursively
> and then back up deleteing a directory if it is found to be empty.

In general, the place to look for these things in the
stdlib is usually shutil. (Slightly awkward that
"shell" in Windows means everything that happens on
the desktop, while "shell" in Unix means everything
*except* what happens on the desktop! This is the
Unix meaning.)

And sure enough...

rmtree( path[, ignore_errors[, onerror]]) 

Delete an entire directory tree (path must point to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception. 
If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo. The first parameter, function, is the function which raised the exception; it will be os.listdir(), os.remove() or os.rmdir(). The second parameter, path, will be the path name passed to function. The third parameter, excinfo, will be the exception information return by sys.exc_info(). Exceptions raised by onerror will not be caught. 



More information about the Python-list mailing list