Glob search files in date order? Glob search files in date order? python python

Glob search files in date order?


To sort files by date:

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

See also Sorting HOW TO.


Essentially the same as @jfs but in one line using sorted

import os,globsearchedfiles = sorted(glob.glob("*cycle*.log"), key=os.path.getmtime)


Well. The answer is nope. glob uses os.listdir which is described by:

"Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory."

So you are actually lucky that you got it sorted. You need to sort it yourself.

This works for me:

import globimport osimport timesearchedfile = glob.glob("*.cpp")files = sorted( searchedfile, key = lambda file: os.path.getctime(file))for file in files: print("{} - {}".format(file, time.ctime(os.path.getctime(file))) )

Also note that this uses creation time, if you want to use modification time, the function used must be getmtime.