我知道使用 Boto 2 可以将 S3 对象作为字符串打开:get_contents_as_string()
boto3 中是否有等效功能?
我知道使用 Boto 2 可以将 S3 对象作为字符串打开:get_contents_as_string()
boto3 中是否有等效功能?
read
将返回字节。至少对于 Python 3,如果要返回字符串,则必须使用正确的编码进行解码:
import boto3
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8')
.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'))
这不在 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
将整个对象主体解码为一个字符串:
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())
如果正文包含 io.StringIO,则必须执行以下操作:
object.get()['Body'].getvalue()