Retrieve S3 file as Object instead of downloading to absolute system path

前端 未结 3 1327
遇见更好的自我
遇见更好的自我 2020-12-08 07:51

I just started learning and using S3, read the docs. Actually I didn\'t find anything to fetch the file into an object instead of downloading it from S3? if this could be po

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 08:16

    I prefer this approach, equivalent to a previous answer:

    import boto3
    s3 = boto3.resource('s3')
    def read_s3_contents(bucket_name, key):
        response = s3.Object(bucket_name, key).get()
        return response['Body'].read()
    

    But another approach could read the object into StringIO:

    import StringIO
    import boto3
    s3 = boto3.resource('s3')
    def read_s3_contents_with_download(bucket_name, key):
        string_io = StringIO.StringIO()
        s3.Object(bucket_name, key).download_fileobj(string_io)
        return string_io.getvalue()
    

提交回复
热议问题