[Python-Dev] os.path.walk() lacks 'depth first' option
Guido van Rossum
guido@python.org
Tue, 13 May 2003 11:40:53 -0400
How about this patch?
Index: os.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/os.py,v
retrieving revision 1.70
diff -c -c -r1.70 os.py
*** os.py 25 Apr 2003 07:11:48 -0000 1.70
--- os.py 13 May 2003 15:40:21 -0000
***************
*** 203,209 ****
__all__.extend(["makedirs", "removedirs", "renames"])
! def walk(top, topdown=True):
"""Directory tree generator.
For each directory in the directory tree rooted at top (including top
--- 203,209 ----
__all__.extend(["makedirs", "removedirs", "renames"])
! def walk(top, topdown=True, onerror=None):
"""Directory tree generator.
For each directory in the directory tree rooted at top (including top
***************
*** 232,237 ****
--- 232,243 ----
dirnames have already been generated by the time dirnames itself is
generated.
+ By default errors from the os.listdir() call are ignored. If
+ optional arg 'onerror' is specified, it should be a function;
+ it will be called with one argument, an exception instance. It
+ can report the error to continue with the walk, or raise the
+ exception to abort the walk.
+
Caution: if you pass a relative pathname for top, don't change the
current working directory between resumptions of walk. walk never
changes the current directory, and assumes that the client doesn't
***************
*** 259,265 ****
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = listdir(top)
! except error:
return
dirs, nondirs = [], []
--- 265,273 ----
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = listdir(top)
! except error, err:
! if onerror is not None:
! onerror(err)
return
dirs, nondirs = [], []
***************
*** 274,280 ****
for name in dirs:
path = join(top, name)
if not islink(path):
! for x in walk(path, topdown):
yield x
if not topdown:
yield top, dirs, nondirs
--- 282,288 ----
for name in dirs:
path = join(top, name)
if not islink(path):
! for x in walk(path, topdown, onerror):
yield x
if not topdown:
yield top, dirs, nondirs
--Guido van Rossum (home page: http://www.python.org/~guido/)