【问题标题】:Write dictionary content to files with keys as filename使用键作为文件名将字典内容写入文件
【发布时间】:2022-01-11 01:51:42
【问题描述】:

我在一个名为“month_data”的对象中有一个字典,其中包含作为值的列表。

    {
     '2000-01': [
      {
        'lat': 52.54,
        'lon': 13.54,
        'timestamp': '2000-01-01 01:00:00',
        'temp': -0.57,
        'feels_like': -2.64,
        'humidity': 97,
        'pressure': 1024
    },
    {
        'lat': 52.54,
        'lon': 13.54,
        'timestamp': '2000-01-01 02:00:00',
        'temp': -0.38,
        'feels_like': -2.46,
        'humidity': 97,
        'pressure': 1024
      }
    ], 
    '2000-02': [
    {
        'lat': 52.54,
        'lon': 13.54,
        'timestamp': '2000-01-01 01:00:00',
        'temp': -0.57,
        'feels_like': -2.64,
        'humidity': 97,
        'pressure': 1024
    },
    {
        'lat': 52.54,
        'lon': 13.54,
        'timestamp': '2000-01-01 02:00:00',
        'temp': -0.38,
        'feels_like': -2.46,
        'humidity': 97,
        'pressure': 1024
      }
    ]
  } 

我想将内容写入 s3 存储桶中的单独文件,但到目前为止它失败了。 错误是:

ParamValidationError: Parameter validation failed: 代码如下:

for month, data in month_data.items():
    s3.put_object(Bucket=s3_bucket, Body=data ,Key=f"{month}.json")

有人知道为什么会失败吗?

谢谢

一个

【问题讨论】:

  • 打印月份和数据变量的类型,看看是否有效或可以接受传递给函数put_object()
  • Body 输入参数必须是字节或类似对象的可搜索文件,参考 boto3 document

标签: python amazon-s3 boto3


【解决方案1】:

您似乎正在尝试将数据保存为 JSON,因此您应该使用 json.dumps 编写一个 JSON 字符串,如下所示:

import boto3
import json

s3 = boto3.client("s3")

s3_bucket = "mybucket"
month_data = { ... }

for month, data in month_data.items():
    s3.put_object(
        Bucket=s3_bucket, Body=json.dumps(data), Key=f"{month}.json"
    )

【讨论】:

  • 感谢@jarmod 就是这样
猜你喜欢
  • 1970-01-01
  • 2019-05-04
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多