How to use glob() to find files recursively?

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

    Another way to do it using just the glob module. Just seed the rglob method with a starting base directory and a pattern to match and it will return a list of matching file names.

    import glob
    import os
    
    def _getDirs(base):
        return [x for x in glob.iglob(os.path.join( base, '*')) if os.path.isdir(x) ]
    
    def rglob(base, pattern):
        list = []
        list.extend(glob.glob(os.path.join(base,pattern)))
        dirs = _getDirs(base)
        if len(dirs):
            for d in dirs:
                list.extend(rglob(os.path.join(base,d), pattern))
        return list
    

提交回复
热议问题