Search code examples
pythonglob

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.


Solution

  • 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