【问题标题】:How to write JSON to file without overwriting the existing value? I want to extend a list [duplicate]如何在不覆盖现有值的情况下将 JSON 写入文件?我想扩展一个列表[重复]
【发布时间】:2021-05-24 09:50:50
【问题描述】:
@commands.command()
        data = {}
        data[f'intros'] = []

        await ctx.send("**Let's create your intro...**")
        await ctx.send("What's your name?")
        name = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
        await ctx.send("How old are you?")
        age = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
        await ctx.send("Where are you from?")
        location = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
        await ctx.send("What about your interests?")
        interests = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)

        
        data['intros'][f'{ctx.author.id}']
            {
                'name': f'{name.content}',
                'age': f'{age.content}',
                'location': f'{location.content}',
                'interests': f'{interests.content}'
            }
        })
    
    with open('./cogs/intros.json', 'w') as outfile:
            json.dump(data, outfile, indent=4)

{
    "intros": [
        {
            "813285103757295666": {
                "name": "a",
                "age": "b",
                "location": "c",
                "interests": "d"
            }
        }
    ]
}

我正在创建一个 discord.py 机器人,并且我正在尝试创建一个介绍系统,以便它将值存储在一个 json 文件 (intro.json) 中。这些值使用用户 ID 存储。当我执行命令时,它会根据需要存储值,但当另一个用户执行它时,它会覆盖现有值。

我希望它在每次用户执行命令时创建单独的字典。我该怎么做?

【问题讨论】:

    标签: python json discord.py


    【解决方案1】:

    已经有人评论了类似的内容,但我想我会扩展。我要做的是load the JSON data,添加到intros 数组,然后用更新的数据重写JSON 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      相关资源
      最近更新 更多