如何在循环中修改JSON文件值?实现用户警告次数递增
实现警告次数递增功能
核心实现代码
import json import os from discord.ext import commands @commands.command() async def warn(self, ctx: commands.Context, member: discord.Member): # 初始化或读取警告数据 if not os.path.exists('warns.json'): data = {"users": {}} else: with open('warns.json', 'r', encoding='utf-8') as f: data = json.load(f) user_id_str = f"{member.id}" # 更新警告次数 if user_id_str in data["users"]: # 字符串转整数运算后再转回字符串 current_count = int(data["users"][user_id_str]) data["users"][user_id_str] = str(current_count + 1) else: # 首次警告,初始化为1 data["users"][user_id_str] = "1" # 将更新后的数据写回文件 with open('warns.json', 'w', encoding='utf-8') as f: json.dump(data, f, indent=4) # 反馈结果给用户 await ctx.send(f"{member.mention} 已被警告,当前警告次数:{data['users'][user_id_str]}")
关键细节说明
- 文件读写逻辑:读取用
'r'模式,写入用'w'模式,确保更新后的内容覆盖原文件 - 类型转换处理:你的JSON中警告次数以字符串存储,必须先转为整数完成加法运算,再转回字符串存回,避免类型错误
- 边界场景兼容:自动处理用户首次被警告的情况,避免
KeyError;同时检查文件是否存在,不存在则自动初始化空的警告结构 - 格式可读性:写入文件时用
indent=4参数,让JSON文件保持清晰的缩进格式,方便后续手动查看或修改
内容的提问来源于stack exchange,提问作者Saad-
相关产品推荐
相关产品推荐

