Alex
Alex

Reputation: 165

How to find all text files with Regex?

Hey there. I'm using glob.glob function in order to get a list of all .txt files on a path that i provide. The regex I'm feeding the function as C:\build\*.txt, but it works only for the root directory, and I'd like to find all text files in c:\build\, also c:\build\files\ha.txt for example.

How is it possible? Thankss.

Upvotes: 0

Views: 4512

Answers (2)

unholysampler
unholysampler

Reputation: 17321

glob doesn't use regular expressions, it has a much simpler set of rules.

An alternative would be to use os.walk() and perform the title matching yourself with a regular expression.

Upvotes: 0

Miguel Ventura
Miguel Ventura

Reputation: 10458

Notice that glob.glob will accept unix shell wildcards and not regex objects (see the documentation).

You might accomplish the feat of getting all .txt files from all sub directories by using os.walk. A method to give you such a list could be something like this:

def get_all_txts_on_dir(path):
    import os
    ret = []
    for root, dir, files in os.walk(path):
        for name in files:
            if name.endswith('.txt'):
                ret.append(name)
    return ret

Upvotes: 5

Related Questions