Completely Deleting A Directory

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Mon Apr 26 05:09:53 EDT 2010


It doesn’t seem to mention in the documentation for os.walk 
<http://docs.python.org/library/os.html> that symlinks to directories are 
returned in the list of directories, not the list of files. This will lead 
to an error in the os.rmdir call in the example directory-deletion routine 
on that page.

This version fixes that problem.

def delete_dir(dir) :
    """deletes dir and all its contents."""
    if os.path.isdir(dir) :
        for parent, dirs, files in os.walk(dir, topdown = False) :
            for item in files :
                os.remove(os.path.join(parent, item))
            #end for
            for item in dirs :
                item = os.path.join(parent, item)
                (os.rmdir, os.remove)[os.path.islink(item)](item)
            #end for
        #end for
        os.rmdir(dir)
    #end if
#end delete_dir




More information about the Python-list mailing list