pradeepln4
pradeepln4

Reputation: 131

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

I have to read the latest image in a folder using python. How can I do this?

Upvotes: 1

Views: 3735

Answers (2)

lemonhead
lemonhead

Reputation: 5518

Another similar way, with some pragmatic (non-foolproof) image validation added:

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) 

Upvotes: 6

Anthon
Anthon

Reputation: 76682

Walk over the filenames, get their modification time and keep track of the latest modification time you found:

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)

Upvotes: 2

Related Questions