How to use glob() to find files recursively?

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

    Similar to other solutions, but using fnmatch.fnmatch instead of glob, since os.walk already listed the filenames:

    import os, fnmatch
    
    
    def find_files(directory, pattern):
        for root, dirs, files in os.walk(directory):
            for basename in files:
                if fnmatch.fnmatch(basename, pattern):
                    filename = os.path.join(root, basename)
                    yield filename
    
    
    for filename in find_files('src', '*.c'):
        print 'Found C source:', filename
    

    Also, using a generator alows you to process each file as it is found, instead of finding all the files and then processing them.

提交回复
热议问题