[Python-Dev] os.path.walk() lacks 'depth first' option
Walter Dörwald
walter@livinglogic.de
Tue, 13 May 2003 18:14:51 +0200
Guido van Rossum wrote:
> How about this patch?
I like the increased flexibility. But how about the following
version?
---
def walk(top, order=".d", recursive=True, onerror=None):
from os.path import join, isdir, islink, normpath
try:
names = listdir(top)
except error, err:
if onerror is not None:
onerror(err)
return
dirs, nondirs = [], []
for name in names:
if isdir(join(top, name)):
dirs.append(name)
else:
nondirs.append(name)
for c in order:
if c==".":
yield top, dirs, nondirs
elif c=="f":
for nd in nondirs:
yield normpath(join(top, nd)), [], []
elif c=="d":
for name in dirs:
path = join(top, name)
if not islink(path):
if recursive:
for x in walk(path, order, recursive, onerror):
yield (normpath(x[0]), x[1], x[2])
else:
yield path
else:
raise ValueError, "unknown order %r" % c
---
It combines recursive and non-recursive walks, topdown and bottomup
walks, walks with and without files or directories.
E.g. Getting a list of all files, topdown:
[x[0] for x in os.walk(top, order="fd")]
or a list of directories bottom up:
[x[0] for x in os.walk(top, order="d.")]
or a list of files and directories, topdown, with
files before subdirectories:
[x[0] for x in os.walk(top, order=".fd")]
Bye,
Walter Dörwald