【问题标题】:How to store python dict in json file from mutiple runs?如何从多次运行中将python dict存储在json文件中?
【发布时间】:2021-07-09 17:16:05
【问题描述】:

我正在尝试将用户输入的数据存储在 dict 中的 .json 文件中。我正在使用

d = data
with open('file.json', 'a') as save_file:
     convert_file.write(json.dumps(d))

但是当我尝试用

打印数据时
with open('file.json') as f:
     filedata = [json.loads(line) for line in f]
print(filedata)    

我收到一个错误,因为 json 文件搞砸了。

{"dict1": {"a": ["1", "2"], "Name": "test"}}{"dict2": {"a": ["3", "4"], "Name": "test2"}}

如何将我的字典写入文件而不弄乱格式?

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    在json字符串之间添加换行符:

    d = data
    with open('file.json', 'a') as save_file:
         convert_file.write(json.dumps(d) + '\n')
    

    您使用的这种格式是 json 行格式。您在每一行中放置一个有效的 json,因此是换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2019-10-23
      • 2020-07-23
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      相关资源
      最近更新 更多