为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Python中编辑编码的json文件

如何在Python中编辑编码的json文件

小怪兽爱吃肉 2024-01-15 15:30:38
我目前正在使用 Python 开发一个 Discord 机器人。为了保存数据,我创建了一个 .tmp 文件来存储 json 格式的数据文本。我必须对其进行编码才能立即写入文件(我还在文件中进行了一些值检查)。因为它是编码的,所以我无法使用以下代码编辑 json:emojiU = '\N{THUMBS UP SIGN}'emojiD = '\N{THUMBS DOWN SIGN}'cnd_Member = [member for member in ctx.guild.members if str(data['roles_id']['AmongUs']) in str(member.roles) and (str(member.status) == "online" or str(member.status) == "idle") and member.id != ctx.author.id]tmpfile = open("my_file.tmp", "wb+", 0) #List that store connected user with a specific rolefor i, member in enumerate(cnd_Member): # for connected member with the specific role    DM = discord.utils.get(client.get_all_members(), id=member.id)    Sstring = "***" + Sender + "***" + '   veux jouer à  ***' + game + '***.\n :thumbsup:  si vous êtes chaud ou  :thumbsdown:  si vous ne l\'êtes pas'    msg = await DM.send(embed=createEbd(des=Sstring, img=imgLink)) #send DM to the member    if i == 0       save = '{{"{}":{{"msgId":{}, "reaction":"None"}}, '.format(member.id, msg.id)    elif i == len(list(cnd_Member))-1:         save = '"{}":{{"msgId":{}, "reaction":"None"}}}}'.format(member.id, msg.id)    else :         save = '"{}":{{"msgId":{}, "reaction":"None"}}, '.format(member.id, msg.id)    await msg.add_reaction(emojiU ) #Bot add reaction to the DM message    await msg.add_reaction(emojiD) #Bot add reaction to the DM message    tmpfile.write(save.encode("utf-8")) #creating the json file with data使用 json.dumps 然后对其进行编码并使用 tmpfile.write 将其写入文件中是可行的,但它只附加数据,而不是编辑 tmpfile 中现有的 json。
查看完整描述

1 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

我找到了如何处理它。

我将所有数据存储在 JSON 格式文件中,当用户添加反应时,它会编辑该文件。当我需要发布表时,它会读取 JSON 文件。

编码或未编码,我只需编辑json.loads并重写文件即可工作


查看完整回答
反对 回复 2024-01-15
  • 1 回答
  • 0 关注
  • 46 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信