Json覆盖上一行

2024-10-04 07:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有一个很大的问题,在过去的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=(',', ':'))

Tags: 文件代码idjsonqueueaswith互联网
1条回答
网友
1楼 · 发布于 2024-10-04 07:27:05

您没有将密钥添加到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=(',', ':'))

相关问题 更多 >