How to use glob() to find files recursively?

前端 未结 28 1844
天涯浪人
天涯浪人 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:28

    That one uses fnmatch or regular expression:

    import fnmatch, os
    
    def filepaths(directory, pattern):
        for root, dirs, files in os.walk(directory):
            for basename in files:
                try:
                    matched = pattern.match(basename)
                except AttributeError:
                    matched = fnmatch.fnmatch(basename, pattern)
                if matched:
                    yield os.path.join(root, basename)
    
    # usage
    if __name__ == '__main__':
        from pprint import pprint as pp
        import re
        path = r'/Users/hipertracker/app/myapp'
        pp([x for x in filepaths(path, re.compile(r'.*\.py$'))])
        pp([x for x in filepaths(path, '*.py')])
    

提交回复
热议问题