gpt4 book ai didi

python - 相当于boto3中的get_contents_to_file

转载 作者:太空狗 更新时间:2023-10-29 17:47:39 28 4
gpt4 key购买 nike

在boto3中,有没有等价于get_contents_to_file的? , 将对象的内容复制到文件句柄?

在 boto 中,如果我有一个 S3 对象 key,我可以将内容复制到一个临时文件中:

from tempfile import TemporaryFile
key = code_that_gets_key()

with TemporaryFile() as tmp_file:
key.get_contents_to_file(key, tmpfile)

我还没有在 boto3 中找到等效项。

我已经能够替换 get_contents_to_filename 的用法与 download_file .但是,这涵盖了我提供文件名的情况。在这种情况下,我想提供文件句柄作为参数。

目前,我可以通过如下遍历主体来使代码在 boto3 中工作:

with TemporaryFile() as tmp_file:
body = key.get()['Body']
for chunk in iter(lambda: body.read(4096), b''):
filehandle.write(chunk)

在 boto3 中有更好的方法吗?

最佳答案

截至V1.4.0有一个download_fileobj完全符合您要求的功能。根据正式文档:

import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
obj = bucket.Object('mykey')

with open('filename', 'wb') as data:
obj.download_fileobj(data)

该操作也可在 bucket resource 上使用和 s3 client还有,例如:

import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')

with open('filename', 'wb') as data:
bucket.download_fileobj('mykey', data)

关于python - 相当于boto3中的get_contents_to_file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136307/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com