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

后端 未结 7 1049
借酒劲吻你
借酒劲吻你 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-12 00:12

    Variation of the answer I provided for: Boto3 S3, sort bucket by last modified. You can modify the code to suit to your needs.

    get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))
    
    s3 = boto3.client('s3')
    objs = s3.list_objects_v2(Bucket='my_bucket')['Contents']
    last_added = [obj['Key'] for obj in sorted(objs, key=get_last_modified)][0]
    

    If you want to reverse the sort:

    [obj['Key'] for obj in sorted(objs, key=get_last_modified, reverse=True)][0]
    

提交回复
热议问题