4

I'd like to get a list of files that apply to a regex that i have. I guess i should use os.walk, but how can i use it with regex?

Thanks.

Alex
  • 165
  • 1
  • 3
  • 6
  • 5
    Please post some code that you tried to use. Please post your proposed solution including any error messages you're getting. This isn't `www.do-my-job-for-me.com` – S.Lott Jan 09 '11 at 14:00

2 Answers2

8

I'm not aware of anything in the stdlib implementing this, but it is not hard to code:

import os, os.path

def iter_matching(dirpath, regexp):
    """Generator yielding all files under `dirpath` whose absolute path
       matches the regular expression `regexp`.
       Usage:

           >>> for filename in iter_matching('/', r'/home.*\.bak'):
           ....    # do something
    """
    for dir_, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            abspath = os.path.join(dir_, filename)
            if regexp.match(abspath):
                yield abspath

Or the more general:

import os, os.path

def filter_filenames(dirpath, predicate):
    """Usage:

           >>> for filename in filter_filenames('/', re.compile(r'/home.*\.bak').match):
           ....    # do something
    """
    for dir_, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            abspath = os.path.join(dir_, filename)
            if predicate(abspath):
                yield abspath
albertov
  • 2,314
  • 20
  • 15
5

If your regex can be translated into a shell expression such as foo/*.txt then you can use glob.

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
moinudin
  • 134,091
  • 45
  • 190
  • 216