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

我目前正在使用 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 role


for 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。


小怪兽爱吃肉
浏览 55回答 1
1回答

白衣染霜花

我找到了如何处理它。我将所有数据存储在 JSON 格式文件中,当用户添加反应时,它会编辑该文件。当我需要发布表时,它会读取 JSON 文件。编码或未编码,我只需编辑json.loads并重写文件即可工作
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python