Python: find the most recently modified file matching a pattern

python-logoWhether it is the most recent log file, image, or report –  sometimes you will need to find the most recently modified file in a directory.  The example below finds the latest file in the “/tmp” directory.

import os
import glob

# get list of files that matches pattern
pattern="/tmp/*"
files = list(filter(os.path.isfile, glob.glob(pattern)))

# sort by modified time
files.sort(key=lambda x: os.path.getmtime(x))

# get last item in list
lastfile = files[-1]

print("Most recent file matching {}: {}".format(pattern,lastfile))

This pattern could easily be changed to find the latest PDF reports “/tmp/*.pdf” or any other pattern.

This code can be found on github as most_recent_file.py