The shortest code: find the latest ctime, then get all files having this latest ctime:
def most_recent(paths):
if not paths:
return []
latest_ctime = max(os.path.getctime(p) for p in paths)
most_recent_files = [p for p in paths if os.path.getctime(p)==latest_ctime]
return most_recent_files
We loop twice over the list of paths, though, and there is a risk of race condition if the ctime of the most recent file changes between the two loops: in this case, it wouldn't be found again in the second loop.
We can do it in one loop, with a little bit more code, eliminating the race condition:
def most_recent_one_loop(paths):
out = []
latest_ctime = 0
for p in paths:
ct = os.path.getctime(p)
if ct > latest_ctime:
latest_ctime = ct
out = [p]
elif ct == latest_ctime:
out.append(p)
return out
As we can expect, this is about twice as fast (about 100 paths in the folder for the test):
%timeit most_recent(paths)
# 1000 loops, best of 3: 477 µs per loop
%timeit most_recent_one_loop(paths)
# 1000 loops, best of 3: 239 µs per loop