Gadfly-1.0rc1 Errors

Andrew Dalke dalke at dalkescientific.com
Sat May 18 21:24:05 EDT 2002


David LeBlanc:
>This is not failing because a file is open imo; it's failing because you're
>trying to remove an non-empty directory. Windows won't do that directly. It
>would be nice if shutils.rmtree took an '-f' flag analgous to the force
flag
>of rm on Unix and did the right thing on windows, which is delete all the
>files in the selected dir(s) and then deleted the directory(s).

Doesn't shutil.rmtree do exactly that?  At the end of this email
is the relevant code.  The '_build_cmd_tuple' creates a list of
terms of the form
   (function, string)
which when applied in order remove all the files and directories
under the given path.  They are sorted so all the files in a directory
are listed first, followed by the directory.

In other words, it does delete all the files in a directory first
and only then deletes the directory.  Which is what you wanted.

def rmtree(path, ignore_errors=0, onerror=None):
    """Recursively delete a directory tree.

    If ignore_errors is set, errors are ignored; otherwise, if
    onerror is set, it is called to handle the error; otherwise, an
    exception is raised.

    """
    cmdtuples = []
    _build_cmdtuple(path, cmdtuples)
    for cmd in cmdtuples:
        try:
            apply(cmd[0], (cmd[1],))
        except:
            exc = sys.exc_info()
            if ignore_errors:
                pass
            elif onerror:
                onerror(cmd[0], cmd[1], exc)
            else:
                raise exc[0], (exc[1][0], exc[1][1] + ' removing '+cmd[1])

# Helper for rmtree()
def _build_cmdtuple(path, cmdtuples):
    for f in os.listdir(path):
        real_f = os.path.join(path,f)
        if os.path.isdir(real_f) and not os.path.islink(real_f):
            _build_cmdtuple(real_f, cmdtuples)
        else:
            cmdtuples.append((os.remove, real_f))
    cmdtuples.append((os.rmdir, path))


                    Andrew
                    dalke at dalkescientific.com







More information about the Python-list mailing list