How to use glob() to find files recursively?

前端 未结 28 2199
天涯浪人
天涯浪人 2020-11-21 22:54

This is what I have:

glob(os.path.join(\'src\',\'*.c\'))

but I want to search the subfolders of src. Something like this would work:

<
28条回答
  •  不要未来只要你来
    2020-11-21 23:27

    Here is a solution that will match the pattern against the full path and not just the base filename.

    It uses fnmatch.translate to convert a glob-style pattern into a regular expression, which is then matched against the full path of each file found while walking the directory.

    re.IGNORECASE is optional, but desirable on Windows since the file system itself is not case-sensitive. (I didn't bother compiling the regex because docs indicate it should be cached internally.)

    import fnmatch
    import os
    import re
    
    def findfiles(dir, pattern):
        patternregex = fnmatch.translate(pattern)
        for root, dirs, files in os.walk(dir):
            for basename in files:
                filename = os.path.join(root, basename)
                if re.search(patternregex, filename, re.IGNORECASE):
                    yield filename
    

提交回复
热议问题