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

后端 未结 7 971
借酒劲吻你
借酒劲吻你 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:07

    You should be able to download the latest version of the file using default download file command

    import boto3
    import botocore
    
    BUCKET_NAME = 'mytestbucket'
    KEY = 'fileinbucket.txt'
    
    s3 = boto3.resource('s3')
    
    try:
        s3.Bucket(BUCKET_NAME).download_file(KEY, 'downloadname.txt')
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            print("The object does not exist.")
        else:
            raise
    

    Reference link

    To get the last modified or uploaded file you can use the following

    s3 = boto3.resource('s3')
    my_bucket = s3.Bucket('myBucket')
    unsorted = []
    for file in my_bucket.objects.filter():
       unsorted.append(file)
    
    files = [obj.key for obj in sorted(unsorted, key=get_last_modified, 
        reverse=True)][0:9]
    

    As answer in this reference link states, its not the optimal but it works.

提交回复
热议问题