【问题标题】:Json overwriting previous lineJson 覆盖上一行
【发布时间】:2021-10-27 11:37:18
【问题描述】:

我的代码有一个大问题,过去 3 小时我无法在互联网上找到任何东西,所以我在这里问。我正在尝试将 ctx.guild.id 作为新变量添加到我的 json“queue.json”文件中,但显然每次我运行此代码时,它都不会在新行中添加新变量,而是会覆盖之前添加的变量.这是我的代码:

with open("queue.json", "r") as f:
    Queue = json.load(f)
    if not ctx.guild.id in Queue:
        with open("queue.json", "w") as QueueAddFile:
            NewQueueID = {ctx.guild.id : []}
            json.dump(NewQueueID, QueueAddFile, separators=(',', ':'))

【问题讨论】:

  • 您不能为 json 文件中的键分配多个值,因此当您执行此操作时,它基本上会覆盖旧值。
  • @AnatoleSot 但它只在 ID 不在字典中时运行
  • 您没有将 ctx.guild.id 添加为 json 中的新键,而是将其设置为 only 键。您需要执行Queue[ctx.guild.id] = [] 之类的操作并将Queue 写回文件。
  • ctx.guild.id 总是不同的数字,所以应该没有问题
  • 再次声明,您没有在此处添加新密钥。您写入文件的 json 仅包含您的新值,没有其他内容。你已经扔掉了 Queue 中的所有内容。

标签: python json python-3.x discord.py


【解决方案1】:

您没有将密钥添加到 Queue 字典,而是创建了一个新字典,其中只有一个新 ID。因此,当您重写文件时,您将丢弃所有其他键。

with open("queue.json", "r") as f:
    Queue = json.load(f)
if ctx.guild.id not in Queue:
    Queue[ctx.guild.id] = []
    with open("queue.json", "w") as QueueAddFile:
        json.dump(Queue, QueueAddFile, separators=(',', ':'))

【讨论】:

  • 非常感谢!它可以根据需要完美运行,我认为如果此变量不在文件本身中,我将无法使用 Queue[Variable]
  • 你不能 Queue[variable],但你当然可以它。您还如何创建新的字典条目?
猜你喜欢
  • 2012-04-09
  • 2012-07-02
  • 2017-04-07
  • 1970-01-01
  • 2019-07-26
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
相关资源
最近更新 更多