The other questions I could find were refering to an older version of Boto. I would like to download the latest file of an S3 bucket. In the documentation I found that there
This is basically the same answer as helloV in the case you use Session as I'm doing.
from boto3.session import Session
import settings
session = Session(aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
s3 = session.resource("s3")
get_last_modified = lambda obj: int(obj.last_modified.strftime('%s'))
bckt = s3.Bucket("my_bucket")
objs = [obj for obj in bckt.objects.all()]
objs = [obj for obj in sorted(objs, key=get_last_modified)]
last_added = objs[-1].key
Having objs sorted allows you to quickly delete all files but the latest with
for obj in objs[:-1]:
s3.Object("my_bucket", obj.key).delete()