How to download the latest file of an S3 bucket using Boto3?

后端 未结 7 1046
借酒劲吻你
借酒劲吻你 2021-01-11 23:22

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

7条回答
  •  孤独总比滥情好
    2021-01-11 23:51

    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()
    

提交回复
热议问题