Completely Deleting A Directory

  • Thread starter Lawrence D'Oliveiro
  • Start date
L

Lawrence D'Oliveiro

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
 
M

MrJean1

The answer to 1) is no, due to topdown = False in the call to os.walk.

/Jean

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

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
 
P

Patrick Maupin

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.

They should probably remove that example, and just point the user to
shutil.rmtree() (as they do under the os.rmdir() description).

Regards,
Pat
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top