【问题标题】:How do you append data to json with python?如何使用 python 将数据附加到 json?
【发布时间】:2021-10-01 00:08:51
【问题描述】:

我一直在尝试将一些数据附加到我的不和谐机器人的 python 中的 json 文件中。但是,我只能获取数据来替换其他数据字符串。这是我的代码:

@client.command()
async def banTest(ctx, member: discord.Member, days=0, hours=0, minutes=0, *, reason="None"):
    user = ctx.author
    seconds = 0
    if days == 0 and hours == 0 and minutes == 0:
        moderatorActions = {
            "bans":
                [
                    {
                        "username": f"{member}",
                        "bannedBy": f"{user}",
                        "banDate": f"{datetime.date.today()} at {datetime.datetime.now().time()}",
                        "reason": f"{reason}",
                        "banTimeRemaining": "INDEFINITE"
                    }
                ]
        }
    else:
        hours = hours + (days * 24)
        minutes = minutes + (hours * 60)
        seconds = seconds + (minutes * 60)
        moderatorActions = {
            "bans":
                [
                    {
                        "username": f"{member}",
                        "bannedBy": f"{user}",
                        "banDate": f"{datetime.date.today()} at {datetime.datetime.now().time()}",
                        "reason": f"{reason}",
                        "banTimeRemaining":
                            [
                              {"seconds": [f"{seconds}"]}
                            ]
                    }
                ]
        }
    with open('moderatorActionLogs.json') as f:
        data = json.load(f)
    data.update(moderatorActions)
    with open('moderatorActionLogs.json', 'w') as f:
        json.dump(data, f)

使用方法: /banTest @user#1234 7 5 30 对员工的粗鲁行为

我正在使用这个 json 文件来存储用户在他们的禁令上还剩下多少时间。我将如何将用户添加到此列表中,而不是替换它们?

(另外,任何有关如何每秒从“秒”变量中减去一个以便临时禁止功能实际起作用的帮助都会很棒)

谢谢! (:

【问题讨论】:

    标签: python json discord discord.py


    【解决方案1】:

    试试这样:这只是一个例子,根据你的数据树试试

    import json
    
    with open('moderatorActionLogs.json', 'r+') as f:
        data = json.load(f)
        data['id'] = 134 # <--- add `id` value.
        f.seek(0)        # <--- should reset file position to the beginning.
        json.dump(data, f, indent=4)
        f.truncate()     # remove remaining part
    

    这对你有意义吗?

    【讨论】:

    • 恐怕不行,哈哈!我可以复制/粘贴到我的代码中吗?如果是这样,我应该把它放在哪里,我应该用什么替换它?
    • 我尝试实施您的建议,但没有成功。如果你能告诉我如何以及在哪里把它放进去,那就太好了!谢谢
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2019-12-16
    • 2017-09-22
    • 2018-05-29
    • 2012-10-11
    相关资源
    最近更新 更多