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)
Nice article Chris G. :)
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
This solution solves my problem.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit