[Tutor] bash find equivalent in Python

Karl Pflästerer sigurd@12move.de
Thu Jul 10 21:47:01 2003


On 11 Jul 2003, Magnus Lyckå <- magnus@thinkware.se wrote:

> 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

That is pretty short but I always found os.path.walk a little bit slow.
Some time ago I had a similar problem and I solved it like that (only a
bit customized for that problem here (I didn't search for html files))

import os, os.path

def filelist(d):
    files = []
    
    for file in os.listdir(d):
        fulldir = os.path.join(d, file)
        if os.path.isdir(fulldir):
            flist = [os.path.join(fulldir, x) for x in os.listdir(fulldir) \
                     if os.path.isfile(os.path.join(fulldir, x)) and x.endswith('.html')]
            files.extend(flist)
            files.extend(filelist(fulldir))
    return files


Here that solution compared with os.path.walk was faster.


   Karl
-- 
"Programs must be written for people to read, and only incidentally
for machines to execute."
                -- Abelson & Sussman, SICP (preface to the first edition)