[Tutor] bash find equivalent in Python

Magnus Lyckå magnus@thinkware.se
Thu Jul 10 20:30:01 2003


At 16:44 2003-07-10 -0700, Danny Yoo wrote:
>Another way to do something like 'find' is to use the os.path.walk()
>utility function:
>
>     http://www.python.org/doc/lib/module-os.path.html
>
>but I find DFS() a little easier on the brain... *grin*

Nah, os.path.walk is just the thing here!

 >>> l = []
 >>> def htmlFinder(arg, dirname, fnames):
...     for fn in fnames:
...             if fn.endswith('.html'):
...                     l.append(os.path.join(dirname, fn))
...
 >>> os.path.walk('c:\\', htmlFinder, None)
 >>> for fn in l: print fn

Just read through the help text a few times...

 >>> help(os.path.walk)
Help on function walk in module ntpath:

walk(top, func, arg)

     Directory tree walk with callback function.

     For each directory in the directory tree rooted at top (including top
     itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
     dirname is the name of the directory, and fnames a list of the names of
     the files and subdirectories in dirname (excluding '.' and '..').  func
     may modify the fnames list in-place (e.g. via del or slice assignment),
     and walk will only recurse into the subdirectories whose names remain in
     fnames; this can be used to implement a filter, or to impose a specific
     order of visiting.  No semantics are defined for, or required of, arg,
     beyond that arg is always passed to func.  It can be used, e.g., to pass
     a filename pattern, or a mutable object designed to accumulate
     statistics.  Passing None for arg is common.


--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language