【问题标题】:How to append .json file consist of list with open() append mode?如何附加 .json 文件由具有 open() 附加模式的列表组成?
【发布时间】:2022-01-03 12:35:26
【问题描述】:

例如,我将 TEST.json 写成:

[{"Alice" : 1, "Betty": 2}]

有没有办法追加当前的json

[{"Alice" : 1, "Betty": 2}, {"Alice" : 10, "Betty": 20}]

通过使用“打开附加模式”方法?例如:

with open("TEST.json", "a+") as f:
    json.dump(blablabla)

由于我要编辑大约 6000 万个文件,所以,我不会使用如下代码:

with open("TEST.json", "r") as f:
   data = json.load(f)

appended_data = data.append({"Alice" : 10, "Betty": 20})

with open("TEST.json", "w") as f:
   json.dump(appended_data, f)

【问题讨论】:

  • @Timus 对不起,示例代码刚刚在正文中提交
  • 您能否更具体地说明最后一段代码困扰您的问题:您想避免什么?是重新转储完整数据吗?总的来说,我会说您可以尝试该代码,但将其嵌入到多处理线程组合解决方案(或 asyncio 而不是线程)中?

标签: python json append


【解决方案1】:

我想这就是你要找的东西:

with open('TEST.json', 'w', encoding = 'utf-8') as file:
    json.dump([{"Alice" : 1, "Betty": 2}], file, indent = 4, ensure_ascii = False)

with open('TEST.json', 'r+', encoding = 'utf-8') as file:
    data = json.load(file)
    data.append({"Alice" : 10, "Betty": 20})
    file.seek(0)
    json.dump(data, file, indent = 4, ensure_ascii = False)

【讨论】:

  • 我不这么认为:这与 op 想要避免的代码基本相同,除了少一个 open。我想这个想法更多的是在末尾删除],在开头附加没有[的新数据,等等。否则必须将完整的数据重新写入磁盘。只是我的猜测,也许我错了。
  • @Timus, hmm, mb 最好尽量不要使用[...] 并尽可能坚持正常的json格式
  • @Timus 我正在考虑这个想法,因为在使用写入模式时(我的意思是 'w' 或 'r+',执行时间将随着指数函数的增加而运行
  • @DmitriiDavs 好吧.. 我必须使用列表类型来检查新数据是否与以前的数据重复
猜你喜欢
  • 2022-11-18
  • 2020-09-18
  • 2016-01-01
  • 2010-11-16
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多