Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.walk with regex

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.

like image 248
Alex Avatar asked Oct 19 '25 05:10

Alex


1 Answers

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
like image 181
albertov Avatar answered Oct 20 '25 20:10

albertov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!