How to use glob() to find files recursively?

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

    In addition to the suggested answers, you can do this with some lazy generation and list comprehension magic:

    import os, glob, itertools
    
    results = itertools.chain.from_iterable(glob.iglob(os.path.join(root,'*.c'))
                                                   for root, dirs, files in os.walk('src'))
    
    for f in results: print(f)
    

    Besides fitting in one line and avoiding unnecessary lists in memory, this also has the nice side effect, that you can use it in a way similar to the ** operator, e.g., you could use os.path.join(root, 'some/path/*.c') in order to get all .c files in all sub directories of src that have this structure.

提交回复
热议问题