194

我知道使用 Boto 2 可以将 S3 对象作为字符串打开:get_contents_as_string()

boto3 中是否有等效功能?

4

6 回答 6

313

read将返回字节。至少对于 Python 3,如果要返回字符串,则必须使用正确的编码进行解码:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 
于 2016-02-13T04:41:11.077 回答
143

.get()由于在 AWS Lambda 中使用 Python 2.7,我无法从 S3 读取/解析对象。

我在示例中添加了 json 以显示它变得可解析:)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

注意(对于 python 2.7):我的对象都是 ascii,所以我不需要.decode('utf-8')

注意(对于 python 3.6+):我们移动到 python 3.6 并发现它read()现在返回bytes,所以如果你想从中获取一个字符串,你必须使用:

j = json.loads(obj['Body'].read().decode('utf-8'))

于 2017-03-11T15:52:50.620 回答
82

这不在 boto3 文档中。这对我有用:

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

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

于 2015-08-12T23:07:10.113 回答
37

Python3 + 使用 boto3 API 方法。

通过使用S3.Client.download_fileobj APIPython 类文件对象,可以将 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
于 2019-06-29T03:43:01.313 回答
0

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

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

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

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

当解码为 JSON 时,无需转换为字符串,因为json.loads也接受字节,因为 Python 3.6:

obj = s3.Object(bucket, key).get()
json.loads(obj["Body"].read())
于 2022-01-07T00:08:30.690 回答
-7

如果正文包含 io.StringIO,则必须执行以下操作:

object.get()['Body'].getvalue()
于 2016-11-30T10:02:26.870 回答