How to use glob() to find files recursively?

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

    Here's a solution with nested list comprehensions, os.walk and simple suffix matching instead of glob:

    import os
    cfiles = [os.path.join(root, filename)
              for root, dirnames, filenames in os.walk('src')
              for filename in filenames if filename.endswith('.c')]
    

    It can be compressed to a one-liner:

    import os;cfiles=[os.path.join(r,f) for r,d,fs in os.walk('src') for f in fs if f.endswith('.c')]
    

    or generalized as a function:

    import os
    
    def recursive_glob(rootdir='.', suffix=''):
        return [os.path.join(looproot, filename)
                for looproot, _, filenames in os.walk(rootdir)
                for filename in filenames if filename.endswith(suffix)]
    
    cfiles = recursive_glob('src', '.c')
    

    If you do need full glob style patterns, you can follow Alex's and Bruno's example and use fnmatch:

    import fnmatch
    import os
    
    def recursive_glob(rootdir='.', pattern='*'):
        return [os.path.join(looproot, filename)
                for looproot, _, filenames in os.walk(rootdir)
                for filename in filenames
                if fnmatch.fnmatch(filename, pattern)]
    
    cfiles = recursive_glob('src', '*.c')
    

提交回复
热议问题