Get a list of files sorted by modified date in Python

in #programming6 years ago (edited)

Screenshot from 2018-05-26 13-26-05.png

I needed to create my own image viewer as part of my content creation workflow, which meant I needed a list of images.

First problem is, I need to get PNG, JPG and GIF images, all in the same list.

Second challenge, I need them sorted, but didn't want them in alphabetical order.

So here is the solution!

Get a list of files

using Glob we can get a list of files excluding directories and those that begin with .

And using += we can start to add to this list.

Sort the file list

Now, at this point, we have each type of file in turn.

Using files.sort, um, sorts that for us, bit in alphabetical order.

Modified order

Fortunately, Sort accepts a key parameter, which is a function that is requested for each entry to build the sorting. Whala, we have the ability to sort by getmtime - the modified time.

Now we simply reverse the sort, putting most recent at the top.

Code

import glob
import glob
files = glob.glob("/home/chrisg/Pictures/*.jpg")
files += glob.glob("/home/chrisg/Pictures/*.png")
files += glob.glob("/home/chrisg/Pictures/*.gif")
files.sort(key=os.path.getmtime, reverse=True)

for file in files:
    print(file)

Sort:  

Nice article Chris G. :)

This solution solves my problem.

Coin Marketplace

STEEM 0.20
TRX 0.12
JST 0.029
BTC 61680.81
ETH 3443.96
USDT 1.00
SBD 2.51