我目前正在使用 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
并重寫文件即可工作
添加回答
舉報
0/150
提交
取消