如何使用boto3将文件或数据写入S3对象
·
回答问题
在 boto 2 中,您可以使用以下方法写入 S3 对象:
-
Key.set_contents_from_string()
-
Key.set\contents\from\file()
-
Key.set_contents_from_filename()
-
Key.set\contents\from\stream()
有没有等价的boto 3?将数据保存到存储在 S3 上的对象的 boto3 方法是什么?
Answers
在 boto 3 中,'Key.set_contents_from_' 方法被替换为
-
Object.put()
-
Client.put_object()
例如:
import boto3
some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'
# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)
# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')
或者,二进制数据可以来自读取文件,如比较 boto 2 和 boto 3的官方文档中所述:
存储数据
从文件、流或字符串中存储数据很容易:
按钮 2.x
从 boto.s3.key 导入密钥
key u003d Key('hello.txt')
key.set_contents_from_file('/tmp/hello.txt')
投票 3
s3.Object('mybucket', 'hello.txt').put(Bodyu003dopen('/tmp/hello.txt', 'rb'))
更多推荐

所有评论(0)