My concerns with this code:

  1. Is there a more efficient way to find files by pattern in Python?
  2. Does os.walk() work in Windows?
  3. Is this code pythonic?
  4. Should search() be broken down into 2 functions?
  5. Is it stupid to handle IOError exception by printing the error msg to the console?

#!/usr/bin/env python

Finding files by pattern

import os
import fnmatch
from os.path import join

def search(base, patt):
    ''' Yield files that match a given pattern '''
    for root, dirs, files in os.walk(base):
            for _ in [join(root, _) for _ in files if fnmatch.fnmatch(_, patt)]:
                yield _
        except IOError as error:
            print error

def example_use(d, p):
    ''' Example use of search function '''
    for _ in search(d, p):
        print _

if __name__ == '__main__':
    example_use('/var', '*.log')
  • 1
    \$\begingroup\$ Please no advice on using unix tools like: "sed awk grep egrep find" \$\endgroup\$ Jun 19, 2014 at 23:39

1 Answer 1


Looks quite pythonic. However:

  • _ stands for don't care, akin to famous hunoz. It is not expected to be used in expressions later on; it is a placeholder.

Fot instance, I am totally lost in what

        for _ in [join(root, _) for _ in files if fnmatch.fnmatch(_, patt)]:
            yield _

does actually yield.

  • os.walk() works perfectly well on Windows

  • I don't see how do you want to break search into two functions. What would those functions do?

  • Any usable file matcher should have an option to specify file type (plain vs directory vs link vs etc), attributes, etc.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.