Deleteing empty directories

CinnamonDonkey CinnamonDonkey at googlemail.com
Mon Mar 30 17:25:26 CEST 2009


Revised:

root
   + Dir1
      + Dir2
         + Dir3
   + NotEmptyDir
      File1
   File2

Result:

Root
   + NotEmptyDir
      File1
   File2



---


import os
import shutil

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

    contents = os.listdir( path )

    if len(contents) == 0:
        return True

    return False


def RecurseTree( path ):
    print "RecurseTree( %s )" % (path,)

    if not os.path.isdir( path ):
        print "RecurseTree( %s ) - NOT A DIRECTORY" % (path,)
        return 0

    contents = os.listdir( path )

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

    contents = os.listdir( path )

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



if __name__ == '__main__':
    RecurseTree( r"c:\temp" )


On 30 Mar, 16:14, CinnamonDonkey <CinnamonDon... at googlemail.com>
wrote:
> My understanding was that rmtree removes a whole tree not just the
> empty directories?
>
> eg.
>
> root
>  - file1
>  - file2
>  - dir1
>  - dir2
>   - file3
>   - dir3
>
> I would expect; dir1 and dir3 to be deleted and nothing else touched.
>
> My attempt came up with:
>
> import os
> import shutil
>
> def isDirEmpty( path ):
>     if not os.path.isdir( path ):
>         return False
>
>     contents = os.listdir( path )
>
>     if len(contents) == 0:
>         return True
>
>     return False
>
> def RecurseTree( path ):
>     if not os.path.isdir( path ):
>         return False
>
>     contents = os.listdir( path )
>
>     if len(contents) == 0:
>         print "Deleting Empty Dir '%s'" % (path,)
>         #shutil.rmtree(path)
>
>     else:
>         for item in contents:
>             investigate = "%s\\%s" % (path, item)
>             if os.path.isdir(investigate):
>                 RecurseTree( investigate )
>
> if __name__ == '__main__':
>     RecurseTree( r"c:\temp" )
>
> But I'm not sure what the max recursion depth is in python? Plus I
> think this could be more efficient.
>
> On 30 Mar, 15:59, Tim Golden <m... at timgolden.me.uk> wrote:
>
> > 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.
>
> > """
>
> > TJG
>
>




More information about the Python-list mailing list