如何使用 boto3 将文件或数据写入 S3 对象 [英] How to write a file or data to an S3 object using boto3

查看:36
本文介绍了如何使用 boto3 将文件或数据写入 S3 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 boto 2 中,您可以使用以下方法写入 S3 对象:

In boto 2, you can write to an S3 object using these methods:

是否有 boto 3 等价物?将数据保存到存储在 S3 上的对象的 boto3 方法是什么?

Is there a boto 3 equivalent? What is the boto3 method for saving data to an object stored on S3?

推荐答案

在 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'))

这篇关于如何使用 boto3 将文件或数据写入 S3 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆