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

How to read the latest image in a folder using python?

我必须使用 python 读取文件夹中的最新图像。我该怎么做?

遍历文件名,get their modification time 并跟踪您找到的最新修改时间:

import os
import glob

ts = 0
found = None
for file_name in glob.glob('/path/to/your/interesting/directory/*'):
    fts = os.path.getmtime(file_name)
    if fts > ts:
        ts = fts
        found = file_name

print(found)

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

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)