我知道与Boto 2,它可以打开一个S3对象作为字符串:get_contents_as_string()

boto3中是否有等效的函数?


当前回答

将整个对象体解码为一个字符串:

obj = s3.Object(bucket, key).get()
big_str = obj['Body'].read().decode()

逐行解码对象主体为字符串:

obj = s3.Object(bucket, key).get()
reader = csv.reader(line.decode() for line in obj['Body'].iter_lines())

自Python 3以来,bytes' decode()中的默认编码已经是'utf-8'。

解码为JSON时,不需要转换为字符串,作为JSON。load也接受字节,从Python 3.6开始:

obj = s3.Object(bucket, key).get()
json.loads(obj['Body'].read())

其他回答

如果正文包含io。StringIO,你必须像下面这样做:

object.get()['Body'].getvalue()

Read将返回字节。至少对于Python 3,如果你想返回一个字符串,你必须使用正确的编码来解码:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

将整个对象体解码为一个字符串:

obj = s3.Object(bucket, key).get()
big_str = obj['Body'].read().decode()

逐行解码对象主体为字符串:

obj = s3.Object(bucket, key).get()
reader = csv.reader(line.decode() for line in obj['Body'].iter_lines())

自Python 3以来,bytes' decode()中的默认编码已经是'utf-8'。

解码为JSON时,不需要转换为字符串,作为JSON。load也接受字节,从Python 3.6开始:

obj = s3.Object(bucket, key).get()
json.loads(obj['Body'].read())

这不在boto3文档中。这招对我很管用:

object.get()["Body"].read()

对象是s3对象:http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object

Python3 +使用boto3 API方法。

通过使用S3.Client。download_fileobj API和Python类文件对象,S3对象内容可以检索到内存。

由于检索到的内容是字节,为了将其转换为str,需要对其进行解码。

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