Search code examples
pythonpython-3.xlistpython-os

How to find the first image in a folder?


What I want to achieve is to get the first item in a folder that is a jpg or png image without having to scan the whole folder.

path = os.getcwd()
#List of folders in the path
folders = next(os.walk(path))[1]

#Get the first element
folders_walk = os.walk(path+'\\'+ folder)
firts = next(folders_walk) [2][0]

With this code I get the first element of the folder, but this may or may not be an image. Any advice?


Solution

  • Not sure what you mean by "without having to scan the entire folder". You could use glob(), but that would still scan the entire directory to match the regex.

    Anyway, see a solution below. Can easily modify if you don't want a recursive search (as below) / want a different criterion to determine if a file is an image.

    import os 
    
    search_root_directory = os.getcwd()
    
    # Recursively construct list of files under root directory. 
    all_files_recursive = sum([[os.path.join(root, f) for f in files] for root, dirs, files in os.walk(search_root_directory)], [])
    
    # Define function to tell if a given file is an image
    # Example: search for .png extension.  
    def is_an_image(fpath): 
        return os.path.splitext(fpath)[-1] in ('.png',)
    
    # Take the first matching result. Note: throws StopIteration if not found
    first_image_file = next(filter(is_an_image, all_files_recursive))
    

    Note that the above will be much more efficient (in the recursive case) if sum() (which pre-computes the entire list of files) is omitted and instead a list of files is handled in is_an_image (but the code is less clear that way).