How to get a directory list sorted by date?

Peter Otten __peter__ at web.de
Sun May 15 05:46:13 EDT 2016


cl at isbd.net wrote:

> I have a little Python program I wrote myself which copies images from
> a camera (well, any mounted directory) to my picture archive.  The
> picture archive is simply a directory hierarchy of dates with years at
> the top, then months, then days.
> 
> My Python program simply extracts the date from the image (put there
> by the camera) and copies the image to the appropriate place in the
> picture archive.
> 
> There is one small bit of speeding up done by my program, it checks if
> the file is already in the archive and doesn't copy if it's already
> there.  I don't generally clear pictures off the camera memory cards
> so it's often the case that most of the pcitures are already in the
> archive and all I actually want to do is copy the last couple of weeks
> of new pictures.
> 
> As camera memory card sizes get bigger (and images get more detailed)
> this is beginning to take rather a long time.
> 
> So, to the question, how can I get a list of the files on the memory
> card (i.e. files in a directory) in date/time order, latest first.  I
> can then copy them until the first one I find which is already in the
> archive.  The file date may not *exactly* match the date/time in the
> image file but it will produce the right order which is what I need.
> 
> What I want is a list in the order produced by:-
>     ls --sort=time
> 
> I suppose I could use a system call but that seems a little inelegant.

Personally I'd be worried that something goes wrong with this approach (one 
changed file time leading you to discard many pictures), but to answer the 
question in the subject: you can build the path from name and folder, then 
find the time with os.path.getmtime(), then sort:

def sorted_dir(folder):
    def getmtime(name):
        path = os.path.join(folder, name)
        return os.path.getmtime(path)

    return sorted(os.listdir(folder), key=getmtime, reverse=True)

The same idea will work with pathlib and os.scandir():

def _getmtime(entry):
    return entry.stat().st_mtime

def sd_sorted_dir(folder):
    return sorted(os.scandir(folder), key=_getmtime, reverse=True)

def pl_sorted_dir(folder):
    """folder: a pathlib.Path() object"""
    return sorted(folder.iterdir(), key=_getmtime, reverse=True)





More information about the Python-list mailing list