Open S3 object as a string with Boto3

前端 未结 5 1207
故里飘歌
故里飘歌 2020-12-02 06:13

I\'m aware that with Boto 2 it\'s possible to open an S3 object as a string with: get_contents_as_string()

Is there an equivalent function in boto3 ?

5条回答
  •  死守一世寂寞
    2020-12-02 07:01

    Python3 + Using boto3 API approach.

    By using S3.Client.download_fileobj API and Python file-like object, S3 Object content can be retrieved to memory.

    Since the retrieved content is bytes, in order to convert to str, it need to be decoded.

    import io
    import boto3
    
    client = boto3.client('s3')
    bytes_buffer = io.BytesIO()
    client.download_fileobj(Bucket=bucket_name, Key=object_key, Fileobj=bytes_buffer)
    byte_value = bytes_buffer.getvalue()
    str_value = byte_value.decode() #python3, default decoding is utf-8
    

提交回复
热议问题