How to use glob() to find files recursively?

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

    Here is my solution using list comprehension to search for multiple file extensions recursively in a directory and all subdirectories:

    import os, glob
    
    def _globrec(path, *exts):
    """ Glob recursively a directory and all subdirectories for multiple file extensions 
        Note: Glob is case-insensitive, i. e. for '\*.jpg' you will get files ending
        with .jpg and .JPG
    
        Parameters
        ----------
        path : str
            A directory name
        exts : tuple
            File extensions to glob for
    
        Returns
        -------
        files : list
            list of files matching extensions in exts in path and subfolders
    
        """
        dirs = [a[0] for a in os.walk(path)]
        f_filter = [d+e for d in dirs for e in exts]    
        return [f for files in [glob.iglob(files) for files in f_filter] for f in files]
    
    my_pictures = _globrec(r'C:\Temp', '\*.jpg','\*.bmp','\*.png','\*.gif')
    for f in my_pictures:
        print f
    

提交回复
热议问题