os.walk with regex
Asked Answered
T

2

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.

Tailpipe answered 9/1, 2011 at 13:53 Comment(0)
B
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
Byssinosis answered 9/1, 2011 at 14:48 Comment(0)
M
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']
Mossman answered 9/1, 2011 at 13:54 Comment(1)
Is glob faster than os.walk + regex?Cathexis

© 2022 - 2024 — McMap. All rights reserved.