开发者

How to find all text files with Regex?

Hey there. I'm using glob.glob f开发者_如何学JAVAunction 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜