Completely Deleting A Directory

MrJean1 mrjean1 at gmail.com
Mon Apr 26 17:31:20 CEST 2010


Two comments:

1) Should delete_dir not be called instead of os.rmdir in this line

                (os.rmdir, os.remove)[os.path.islink(item)](item)

2) Function rmtree in the shutil module considers symlinks to a
directory an error <http://docs.python.org/library/shutil.html#module-
shutil> since Python 2.6.

/Jean


On Apr 26, 2:09 am, Lawrence D'Oliveiro <l... at geek-
central.gen.new_zealand> wrote:
> 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