且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 boto3 将文件或数据写入 S3 对象

更新时间:2022-11-07 08:25:06

在 boto 3 中,'Key.set_contents_from_' 方法被替换为

In boto 3, the 'Key.set_contents_from_' methods were replaced by

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 的官方文档:

Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:

从文件、流或字符串存储数据很容易:

Storing Data

Storing data from a file, stream, or string is easy:

# Boto 2.x
from boto.s3.key import Key
key = Key('hello.txt')
key.set_contents_from_file('/tmp/hello.txt')

# Boto 3
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))