Glob search files in date order?

Jason Rogers picture Jason Rogers · May 2, 2014 · Viewed 35.5k times · Source

I have this line of code in my python script. It searches all the files in in a particular directory for * cycle *.log.

for searchedfile in glob.glob("*cycle*.log"):

This works perfectly, however when I run my script to a network location it does not search them in order and instead searches randomly.

Is there a way to force the code to search by date order?

This question has been asked for php but I am not sure of the differences.

Thanks

Answer

jfs picture jfs · May 2, 2014

To sort files by date:

import glob
import os

files = glob.glob("*cycle*.log")
files.sort(key=os.path.getmtime)
print("\n".join(files))

See also Sorting HOW TO.