glob() that traverses a folder tree

Kent Johnson kent at kentsjohnson.com
Thu May 11 16:04:22 EDT 2006


seannakasone at yahoo.com wrote:
> # i'm guessing os.walk() is the best way to traverse folder trees.
> 
> import os, glob
> 
> for dir, subdir, files in os.walk('.\InteropSolution'):
>    for file in files:
>       if glob.fnmatch.fnmatch(file,"*.dll") or
> glob.fnmatch.fnmatch(file,"*.exe"):
>          print dir+file

Or use Jason Orendorff's path module. For a single glob it is very easy:

import path
for f in path.path('.\InteropSolution').walkfiles('*.dll'):
   print f

For multiple globs you have to work a little harder:
for f in path.path('.\InteropSolution').walkfiles():
   if f.fnmatch('*.dll') or f.fnmatch('*.exe'):
     print f

or maybe
for f in path.path('.\InteropSolution').walkfiles():
   if f.ext in ['.dll', '.exe']:
     print f

http://www.jorendorff.com/articles/python/path/index.html

Kent



More information about the Python-list mailing list