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

Discord.py机器人无法创建文件报FileNotFoundError错误求助

问题排查与修复方案

问题原因

  • 错误1:服务器ID格式处理错误
    Discord的guild.id是长整数类型,你强制转成float再转字符串,会被格式化为科学计数法(比如报错中的8.205884699055227e+17),导致文件名和预期完全不符,属于无意义的多余操作。
  • 错误2:父目录不存在未提前创建
    Python内置的open()函数在w模式下仅能创建目标文件,无法自动创建路径中不存在的上级目录,如果json/guilds/db-gc/这个文件夹路径不存在,就会直接抛出FileNotFoundError。

修复步骤

  1. 首先导入os模块用于创建目录:
import os
  1. 删掉多余的float转换逻辑,直接将guild.id转为字符串即可
  2. 写文件前先判断并创建父目录,避免路径不存在报错
  3. 建议替换print写JSON的方式,改用json.dump保证格式规范不易出错

修复后完整代码

@client.command()
async def chat_filter(ctx, val = None):
  guild = ctx.guild
  with open(f"json/guilds/config.json", "r") as f:
    load = json.load(f)
  if guild.id in load["ids"]:
    print("The Guild Is Registerred")
  elif not guild.id in load["ids"]:
    name = str(guild.id)
    # 先创建父目录,exist_ok=True表示目录已存在时不抛出错误
    os.makedirs("json/guilds/db-gc/", exist_ok=True)
    file_path = f"json/guilds/db-gc/{name}.json"
    # 改用with上下文管理和json.dump写文件,更安全规范
    with open(file_path, 'w') as f:
        json.dump({"words": []}, f)
    with open(f"json/guilds/config.json", "r") as f:
      l = json.load(f)
    l["ids"].append(ctx.guild.id)
    with open(f"json/guilds/config.json", "w") as f:
      json.dump(l, f)
  else:
    raise Exception("Some Error")

内容的提问来源于stack exchange,提问作者SARANSH DAS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:00:00