我遇到一個問題,我的 JSON 文件在一段時間后在文件末尾添加了另一個括號,這使得leaderbord 命令無法讀取該文件。這是我的代碼:dict = Counter() @commands.command() async def cupcake(self, ctx): id = str(user.id) if id in dict: dict[user.id] += 1 else: dict[user.id] += 1 with open('users.json', 'r+') as f: json.dump(dict, f)然后,我運行排行榜命令。 @commands.command(pass_context=True) async def top(self, ctx): with open('users.json', 'r') as fg: data = json.load(fg) top_cakes = {k: v for k, v in sorted(data.items(), key=lambda item: item[1], reverse=True)} names = '' for postion, user in enumerate(top_cakes): names += f'<@!{user}> has {top_cakes[user]}\n' embed = discord.Embed(title="Cupcake top", color=0xF9CF7A) embed.add_field(name="Top bakers:", value=names, inline=False) await ctx.send(embed=embed)這是 JSON 文件:(我已替換了實際的用戶 ID){"USERID": 3, "USERID": 2}這是幾次獲得積分后會發生的情況:{"USERID": 1} "USERID": 2}我無法確定它何時發生,它似乎完全是隨機的。經過幾次獲得積分后,它會在名字上添加另一個括號。我不知道該怎么做或如何解決它。
1 回答

冉冉說
TA貢獻1877條經驗 獲得超1個贊
{"USERID": 3, "USERID": 2}
當您編寫類似的內容,然后編寫更短的輸出(例如{"USERID": 1}
;)時,可能會發生這種情況。您的代碼不會以任何方式截斷文件,因此它只會覆蓋開頭,而舊的、較長的輸出的其余部分保留在那里。
可能的解決方案:
以 模式打開文件
'w'
,該模式會在寫入之前截斷文件。.truncate()
寫入文件后顯式截斷文件(使用)。
在這種情況下,以模式打開文件'w'
可能是更好的方法。
添加回答
舉報
0/150
提交
取消