如何使用python读取文件夹中的最新图像?

pra*_*ln4 1 image image-processing python-2.7

我必须使用 python 读取文件夹中的最新图像。我怎样才能做到这一点?

lem*_*ead 5

另一种类似的方式,添加了一些实用的(非万无一失的)图像验证:

import os

def get_latest_image(dirpath, valid_extensions=('jpg','jpeg','png')):
    """
    Get the latest image file in the given directory
    """

    # get filepaths of all files and dirs in the given dir
    valid_files = [os.path.join(dirpath, filename) for filename in os.listdir(dirpath)]
    # filter out directories, no-extension, and wrong extension files
    valid_files = [f for f in valid_files if '.' in f and \
        f.rsplit('.',1)[-1] in valid_extensions and os.path.isfile(f)]

    if not valid_files:
        raise ValueError("No valid images in %s" % dirpath)

    return max(valid_files, key=os.path.getmtime) 
Run Code Online (Sandbox Code Playgroud)