1
\$\begingroup\$

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):
        try:
            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')
\$\endgroup\$
  • 1
    \$\begingroup\$ Please no advice on using unix tools like: "sed awk grep egrep find" \$\endgroup\$ – Ricky Wilson Jun 19 '14 at 23:39
2
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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