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

Discord.py读取json提取ID报'str'对象无read属性错误排查

报错根因

json.load() 方法的入参要求是支持 read() 方法的类文件对象,你直接传入了字符串类型的文件名 'muted.json',字符串对象不存在 read 属性,因此触发 AttributeError: 'str' object has no attribute 'read' 异常。

正确实现代码

基础修复版本(满足绝大多数小体量JSON配置文件的使用场景):

import json

async def listblacklist(ctx):
    # 以只读模式打开JSON文件,指定utf-8编码避免中文/特殊字符乱码
    with open('muted.json', 'r', encoding='utf-8') as file_handler:
        blacklist_data = json.load(file_handler)
    id_list = list(blacklist_data.keys())
    # 后续补充你的命令逻辑,例如返回黑名单列表给频道
    await ctx.send(f"当前黑名单共收录{len(id_list)}个ID:\n" + "\n".join(map(str, id_list)))
注意事项
  • 不要混淆两个JSON解析方法:
    • json.load(文件对象):直接解析已打开的文件流
    • json.loads(JSON格式字符串):解析内存中的JSON字符串,如果你手动先读取了文件内容为字符串,需要用这个方法,示例:
      with open('muted.json', 'r', encoding='utf-8') as f:
          file_content = f.read()
      blacklist_data = json.loads(file_content)
      
  • 优先使用 with 上下文管理器操作文件,会自动完成文件关闭逻辑,不需要手动调用 close(),避免资源泄漏。
  • 如果你的muted.json文件体积较大,同步文件读取会阻塞Discord.py的异步事件循环,导致机器人响应卡顿,可以把IO操作放到独立线程执行:
    import asyncio
    import json
    
    async def listblacklist(ctx):
        def sync_read_json():
            with open('muted.json', 'r', encoding='utf-8') as f:
                return json.load(f)
        blacklist_data = await asyncio.to_thread(sync_read_json)
        id_list = list(blacklist_data.keys())
        # 后续命令逻辑
    

内容的提问来源于stack exchange,提问作者Monster png

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 10:42:21