A little assistance with os.walk please.

Tim Chase python.list at tim.thechases.com
Mon Aug 14 12:43:34 EDT 2006


> 1) there seems to be an optional topdown flag.  Is that passed to
> os.walk(path, topdownFlag)

Yes.

> 2) I only want to process files that match *.txt for example...  Does
> that mean I need to parse the list of files for the .txt extention or
> can I pass a wildcard in the path parameter?

 >>> for path, dirs, files in os.walk("."):
...     for f in files:
...             if not f.lower().endswith(".txt"): continue
...             print os.path.join(path, f)

If you want to be more complex:


 >>> from os.path import splitext
 >>> allowed = ['.txt', '.sql']
 >>> for path, dirs, files in os.walk("."):
...     for f in files:
...             if splitext(f)[1].lower() not in allowed: continue
...             fn = os.path.join(path, f)
...             print "do something with %s" % fn


Just a few ideas,

-tkc











More information about the Python-list mailing list