[ python-Bugs-1071087 ] os.walk example for deleting a full tree is
sometime wrong
SourceForge.net
noreply at sourceforge.net
Mon Nov 22 17:20:39 CET 2004
Bugs item #1071087, was opened at 2004-11-22 17:02
Message generated for change (Comment added) made by bornet
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1071087&group_id=5470
Category: Documentation
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Olivier Bornet (bornet)
Assigned to: Nobody/Anonymous (nobody)
Summary: os.walk example for deleting a full tree is sometime wrong
Initial Comment:
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().
----------------------------------------------------------------------
>Comment By: Olivier Bornet (bornet)
Date: 2004-11-22 17:20
Message:
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.
----------------------------------------------------------------------
Comment By: Tim Peters (tim_one)
Date: 2004-11-22 17:12
Message:
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.
----------------------------------------------------------------------
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1071087&group_id=5470
More information about the Python-bugs-list
mailing list