So my answer can be used for last modified, but I thought that if you've come to this page, there is a chance that'd you like to be able to sort your files in some other manner. So to kill 2 birds with one stone:
In this thread you can find the built-in method sorted. If you read the docs or this article, you will see that you can create your own function to give priority to how objects should be sorted. So for example in my case. I had a bunch of files that had some number in front of them and potentially a letter. It looked like this:
1.svg
10.svg
100a.svg
11.svg
110.svg
...
2.svg
20b.svg
200.svg
...
10011b.svg
...
etc
I wanted it to be sorted by the number up front - I didn't care about the letter behind the number, so I wrote this function:
def my_sort(x):
try:
# this will take the file name, split over the file type and take just the name, cast it to an int, and return it
return int(x.split(".")[0])
# if it couldn't do that
except ValueError:
# it will take the file name, split it over the extension, and take the name
n = x.split(".")[0]
s = ""
# then for each character
for e in n:
# check to see if it is a digit and append it to a string if it is
if e.isdigit():
s += e
# if its not a digit, it hit the character at the end of the name, so return it
else:
return int(s)
Which means now I can do this:
import boto3
s3r = boto3.resource('s3')
bucket = s3r.Bucket('my_bucket')
os = bucket.objects.filter(Prefix="my_prefix/")
os = [o.key.split("/")[-1] for o in os]
os = sorted(os, key=my_sort)
# do whatever with the sorted data
which will sort my files by the numerical suffix in their name.