pythonic tree-walking idioms
Tim Peters
tim.one at home.com
Fri May 18 04:05:06 EDT 2001
[Fredrik Lundh]
> os.path.walk is pretty unpythonic, imo [1].
Mine too, and, luckily for us <wink>, also Guido's: last time this came up,
he said he considers os.path.walk to be a youthful indiscretion. I'm sure it
will never go away, but I never steer people toward it either.
> using an iterator-style "walker" object is usually both faster and
> more convenient.
I always do it by hand!
pending = [dir]
while pending:
dir = pending.pop()
for shortname in os.listdir(dir):
path = os.path.join(dir, shortname)
if os.path.isdir(path):
pending.append(path)
# and whatever processing needs to be done
# goes here
See Neil Schemenauer's post to see how that can be used almost vertabim to
create a generator for producing the paths via the 2.2 iterator protocol (+
his generator patch). Sweet.
More information about the Python-list
mailing list