gpt4 book ai didi

python - 如何使用 boto3 将 S3 对象保存到文件中

转载 作者:IT老高 更新时间:2023-10-28 21:07:00 33 4
gpt4 key购买 nike

我正在尝试用新的 boto3 做一个“hello world” AWS 的客户端。

我的用例相当简单:从 S3 获取对象并将其保存到文件中。

在 boto 2.X 中,我会这样做:

import boto
key = boto.connect_s3().get_bucket('foo').get_key('foo')
key.get_contents_to_filename('/tmp/foo')

在 boto 3 中。我找不到一个干净的方法来做同样的事情,所以我手动迭代“流”对象:

import boto3
key = boto3.resource('s3').Object('fooo', 'docker/my-image.tar.gz').get()
with open('/tmp/my-image.tar.gz', 'w') as f:
chunk = key['Body'].read(1024*8)
while chunk:
f.write(chunk)
chunk = key['Body'].read(1024*8)

import boto3
key = boto3.resource('s3').Object('fooo', 'docker/my-image.tar.gz').get()
with open('/tmp/my-image.tar.gz', 'w') as f:
for chunk in iter(lambda: key['Body'].read(4096), b''):
f.write(chunk)

而且效果很好。我想知道是否有任何“ native ”boto3 函数可以完成相同的任务?

最佳答案

最近在 Boto3 中进行了一项自定义,这有助于解决这个问题(除其他外)。它目前在低级 S3 客户端上公开,可以这样使用:

s3_client = boto3.client('s3')
open('hello.txt').write('Hello, world!')

# Upload the file to S3
s3_client.upload_file('hello.txt', 'MyBucket', 'hello-remote.txt')

# Download the file from S3
s3_client.download_file('MyBucket', 'hello-remote.txt', 'hello2.txt')
print(open('hello2.txt').read())

这些函数将自动处理读取/写入文件以及为大文件并行进行分段上传。

请注意,s3_client.download_file 不会创建目录。它可以创建为 pathlib.Path('/path/to/file.txt').parent.mkdir(parents=True, exist_ok=True).

关于python - 如何使用 boto3 将 S3 对象保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378763/

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