Python 将json写入s3存储桶中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46844263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:52:59  来源:igfitidea点击:

Writing json to file in s3 bucket

pythonboto3

提问by Learning

This code writes json to a file in s3, what i wanted to achieve is instead of opening data.json file and writing to s3 (sample.json) file,

这段代码将json写入s3中的文件,我想要实现的是而不是打开data.json文件并写入s3(sample.json)文件,

how do i pass the json directly and write to a file in s3 ?

我如何直接传递 json 并写入 s3 中的文件?

import boto3

s3 = boto3.resource('s3', aws_access_key_id='aws_key', aws_secret_access_key='aws_sec_key')
s3.Object('mybucket', 'sample.json').put(Body=open('data.json', 'rb'))

采纳答案by Usman Mutawakil

Amazon S3 is an object store (File store in reality). The primary operations are PUT and GET. You can not add data into an existing object in S3. You can only replace the entire object itself.

Amazon S3 是一个对象存储(实际上是文件存储)。主要操作是 PUT 和 GET。您不能将数据添加到 S3 中的现有对象中。您只能替换整个对象本身。

For a list of available operations you can perform on s3 see this link http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectOps.html

有关您可以在 s3 上执行的可用操作列表,请参阅此链接 http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectOps.html

回答by Uwe Bretschneider

I'm not sure, if I get the question right. You just want to write JSON data to a file using Boto3? The following code writes a python dictionary to a JSON file.

我不确定,如果我问对了问题。您只想使用 Boto3 将 JSON 数据写入文件?以下代码将 Python 字典写入 JSON 文件。

import json
import boto3    
s3 = boto3.resource('s3')
s3object = s3.Object('your-bucket-name', 'your_file.json')

s3object.put(
    Body=(bytes(json.dumps(json_data).encode('UTF-8')))
)