You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python用JSON读写文件存储字典及TypeError类型报错解决

问题根因
  • 直接调用f.writelines(w)传入字典对象不符合方法要求:writelines()仅支持传入字符串组成的可迭代对象,你需要先将修改后的字典序列化为JSON格式字符串才能写入文件。
  • 隐藏问题1:JSON规范仅支持字符串类型作为键,exc.author.id为int类型,直接作为键存入后,下次加载时用int类型的ID查询会匹配不到对应值。
  • 隐藏问题2:你使用r+模式打开文件,读取完全部内容后文件指针位于文件末尾,直接写入新内容会追加到旧内容之后,导致JSON格式损坏无法加载。
修复方案

最简可运行代码

import json

@bot.command()
async def register(exc):
    # 读取原有JSON字典
    with open("accounts.txt", "r", encoding="utf-8") as f:
        account_dict = json.load(f)
    # 转换用户ID为字符串后添加键值对
    account_dict[str(exc.author.id)] = "some"
    # 覆盖写入新的JSON内容
    with open("accounts.txt", "w", encoding="utf-8") as f:
        json.dump(account_dict, f, ensure_ascii=False, indent=2)

改动说明

  • 用json.dump()方法直接完成字典到JSON的序列化+写入文件操作,替代错误的writelines调用
  • 将exc.author.id转为字符串作为键,保证读写时键类型匹配
  • 分读、写两次打开文件,写入时用w模式直接覆盖旧内容,避免JSON格式损坏
  • 使用with上下文管理器自动管理文件句柄,无需手动关闭文件,避免资源泄漏

单文件句柄实现(可选)

如果你想只用一次打开文件完成读写,可以用seek和truncate方法控制指针位置:

import json

@bot.command()
async def register(exc):
    with open("accounts.txt", "r+", encoding="utf-8") as f:
        account_dict = json.load(f)
        account_dict[str(exc.author.id)] = "some"
        f.seek(0) # 将文件指针移动到开头
        json.dump(account_dict, f, ensure_ascii=False, indent=2)
        f.truncate() # 清空指针后残留的旧内容

内容的提问来源于stack exchange,提问作者WORM HACKER

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 09:54:05