How to get a directory list sorted by date?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun May 15 06:48:09 EDT 2016


On Sunday 15 May 2016 18:47, cl at isbd.net wrote:

> What I want is a list in the order produced by:-
>     ls --sort=time

I'm not sure if this is the best way to do it, but what I would do is sort the 
directory list by the file's time metadata, which you can access using os.stat.

To sort the file names, I use a key function which takes the filename, joins it 
to the parent directory, grabs its stat data, and extracts the time field. This 
is done only once per file name.


import os
import functools

def by_date(where, fname):
    return os.stat(os.path.join(where, fname)).st_mtime

location = '/tmp/'
files = sorted(os.listdir(location), key=functools.partial(by_date, location))


The mysterious call to functools.partial creates a new function which is 
exactly the same as by_date except the "where" argument is already filled in. 
If functools.partial scares you, you can replace it with:

key=lambda fname: by_date(location, fname)

and if lambda scares you, you can create a top-level function:

def keyfunc(fname):
    return by_date(location, fname)



Also, remember that most operating systems provide (at least) three different 
times. I'm not sure which one you want, but if I had to guess, I would probably 
guess mtime. If I remember correctly:

atime is usually the last access time;
mtime is usually the last modification time;
ctime is the creation time, but only on OS-X;
ctime on Linux and Windows is, um, something else...

To use one of the other two, change "st_mtime" to "st_ctime" or "st_atime".


-- 
Steve




More information about the Python-list mailing list