如何使用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方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在boto 3中,'key.set_contents_from_'方法被
object.put()
另外,二进制数据可以来自读取文件,如官方文档比较Boto 2和Boto 3 :
In boto 3, the 'Key.set_contents_from_' methods were replaced by
Object.put()
Client.put_object()
For example:
Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:
boto3还具有直接上传文件的方法:
boto3 also has a method for uploading a file directly:
http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.upload_file
在写入S3中的文件之前,您不再需要将内容转换为二进制文件。以下示例在带有字符串内容的S3存储桶中创建一个新的文本文件(称为newfile.txt):
You no longer have to convert the contents to binary before writing to the file in S3. The following example creates a new text file (called newfile.txt) in an S3 bucket with string contents:
这是从S3读取JSON的一个不错的技巧:
现在您可以使用
JSON.LOAD_S3
和JSON.DUMP_S3
,使用相同的API与load> load
和<代码>转储Here's a nice trick to read JSON from s3:
Now you can use
json.load_s3
andjson.dump_s3
with the same API asload
anddump
我用来即可随时将文件上传到给定的S3存储桶和sub-folder- note 的清洁版本
:您应该始终将AWS凭据放置(
aws_access_key_id
和aws_secret_access_key
)在单独的文件中,例如 -〜/.aws/.aws/corterentials
A cleaner and concise version which I use to upload files on the fly to a given S3 bucket and sub-folder-
Note: You should ALWAYS put your AWS credentials (
aws_access_key_id
andaws_secret_access_key
) in a separate file, for example-~/.aws/credentials
经过一些研究,我发现了这个。可以使用简单的CSV作者来实现它。它是直接将CSV的字典写入S3存储桶。
例如:data_dict = [{“ key1”:“ value1”,“ key2”:“ value2”},{“ key1”:“ value4”,“ key2”:“ value3”}]]
假设所有字典中的键都是均匀的。
After some research, I found this. It can be achieved using a simple csv writer. It is to write a dictionary to CSV directly to S3 bucket.
eg: data_dict = [{"Key1": "value1", "Key2": "value2"}, {"Key1": "value4", "Key2": "value3"}]
assuming that the keys in all the dictionary are uniform.
值得一提的是 smart-open 使用
boto3
作为back-结尾。smart-open
是可以从s3
以及ftp open
的倒入替换。 >,HTTP
和许多其他协议。例如
,AWS凭据通过〜/.aws/ dir或环境变量中的文件。
it is worth mentioning smart-open that uses
boto3
as a back-end.smart-open
is a drop-in replacement for python'sopen
that can open files froms3
, as well asftp
,http
and many other protocols.for example
The aws credentials are loaded via boto3 credentials, usually a file in the
~/.aws/
dir or an environment variable.您可以使用以下代码来编写,例如2019年对S3的图像。要能够连接到S3,您必须使用命令
pip install awscli awscli
安装AWS CLI,然后使用一些凭据使用几个凭据命令AWS配置
:You may use the below code to write, for example an image to S3 in 2019. To be able to connect to S3 you will have to install AWS CLI using command
pip install awscli
, then enter few credentials using commandaws configure
: