This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: os.walk example for deleting a full tree is sometime wrong
Type: Stage:
Components: Documentation Versions:
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: tim.peters Nosy List: bornet, tim.peters
Priority: normal Keywords:

Created on 2004-11-22 16:02 by bornet, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (4)
msg23234 - (view) Author: Olivier Bornet (bornet) Date: 2004-11-22 16:02
On page:

http://docs.python.org/lib/os-file-dir.html

the example give:

...
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(join(root, name))
    for name in dirs:
        os.rmdir(join(root, name))

This don't work if one link exist in the tree pointing
to a directory.
Assume for example you have:
/tmp/mydir/a/link which is a link to /tmp/mydir/toto

The given recipe will work until /tmp/mydir/toto is an
existing dir. At this time, link will be returned as a
directory, and doing a "os.rmdir('/tmp/mydir/a/link')"
will fail.

One solution can be:
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(join(root, name))
    for name in dirs:
        try:
            os.rmdir(join(root, name))
        except OSError:
            os.remove(join(root, name))

Another better thing is to use os.path.join() instead
of join().
msg23235 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2004-11-22 16:12
Logged In: YES 
user_id=31435

Shrug -- the point of the example is the need for 
topdown=False, not to illustrate platform-dependent 
headaches created by links.  If this is confusing, I'd rather 
leave the example alone and add words saying the example 
assumes there aren't links.

WRT join(), the example is already using os.path.join().  The

from os.path import join

establishes "join" as a short name for os.path.join.
msg23236 - (view) Author: Olivier Bornet (bornet) Date: 2004-11-22 16:20
Logged In: YES 
user_id=122379

Hi,

thanks for this quick answer. I agree with you that this is
enough to add few words assuming there aren't links.

And sorry for the join. I have missing the from os.path
import join.

Good day.
msg23237 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2004-11-22 16:49
Logged In: YES 
user_id=31435

OK, I added words about links, and changed the example to 
spell out os.path.walk in full (I agree it's clearer that way).  
Thank you for the report!

Doc/lib/libos.tex 1.145
History
Date User Action Args
2022-04-11 14:56:08adminsetgithub: 41204
2004-11-22 16:02:29bornetcreate