【问题标题】:Cannot write into the JSON file无法写入 JSON 文件
【发布时间】:2021-02-19 07:09:08
【问题描述】:

我目前正在为我的不和谐机器人制作一个徽章系统,我想要一个命令来修改用户徽章。我已经制作了代码,但它没有编辑它。

我的代码:

@client.command()
@commands.guild_only()
async def modifybadges(ctx, userid, badge):
    try:
        data = get_data()
        for profile in data:
            if profile['discord_id'] == f"{userid}":
                profile = {'discord_id': f"{userid}", 'badges': f"{badge}"}
        await ctx.send(f"Successfully gave user <@{userid}> badge {badge}.")
    except Exception as e:
        await ctx.send(f"error {e}")
def set_data(data):
    with open('profiles.json', 'w') as file:
        file.write(dumps(data, indent=2))

def profile(badges, discord_id, mode):
    data = get_data()
    if mode == 'create':
        data.append({"discord_id": discord_id, "badges": badges})
    elif mode == 'modify':
        for profile in data:
            if profile['discord_id'] == f"{discord_id}":
                profile = {'discord_id': f"{discord_id}", 'badges': f"{badges}"}
    set_data(data)

如果您对如何修复它有任何想法,请在下面留言,谢谢。

【问题讨论】:

  • 请更具体。当你说它'没有编辑它'时,你指的是当你写入文件时:file.write(dumps(data, indent=2))?
  • 是.......................

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


【解决方案1】:

试试这个。如果它不起作用,请提供您收到或发出的错误。

with open('profiles.json', 'w') as file:
    json.dump(data, file)

【讨论】:

    【解决方案2】:
    with open('profiles.json', 'w') as file:
         file.write(dumps(data, indent=4))
    

    **试试这个** 请向我们提供确切的错误

    【讨论】:

    • 你的答案和他的代码之间的唯一区别是缩进是 4 而不是 2。这可能会改变 JSON 的格式,但不会解决他写入文件的问题。跨度>
    猜你喜欢
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多