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

使用Flask与discord开发时创建新文件报只读文件系统错误如何解决

报错根因
  • 路径拼接逻辑错误:你定义directory = f'/{ctx.author.name}'时开头加了/表示绝对路径,调用os.path.join(parent_dir, directory)时,Python会直接忽略前面的parent_dir参数,最终生成的路径是根目录下的/Mewniverse,安卓系统的根目录默认是只读的,直接触发Errno 30 Read-only file system报错。
  • 缺少上级目录预创建逻辑:就算路径拼接正确,如果userFiles/templates目录不存在,直接调用open()创建文件也会抛出找不到路径的异常。
  • 文件名前后不一致:你创建的文件没有.html后缀,但后续render_template读取的是{ctx.author.name}.html,会导致模板找不到报错。
可行修复代码
import os
from flask import render_template

def hello_world(ID):
    username = ctx.author.name
    print(f"Trying to open {username}'s folder")
    # 去掉路径开头的斜杠,统一文件后缀和后续渲染逻辑对齐
    filename = f'{username}.html'
    parent_dir = 'userFiles/templates'
    # 先创建上级目录(如果不存在),exist_ok=True避免已存在时报错
    os.makedirs(parent_dir, exist_ok=True)
    path = os.path.join(parent_dir, filename)

    if os.path.isfile(path):
        print("File exist")
    else:
        print("File not found error raised")
        print("File not accessible. creating new.")
        # 使用上下文管理器自动处理文件关闭,避免资源泄漏
        with open(path, "w") as f:
            f.write("Now the file has more content!")
        print("File created and written in")

    return render_template(filename)
        
# 其余代码保持不变
app.run(host='0.0.0.0', port=8080)
            
await ctx.message.channel.send(f'Here you go {ctx.author.name}! Your site will be here: http://192.168.0.26:8080/{ctx.author.name}')
补充排查点

如果修改后仍有权限问题,可以先打印当前工作目录确认路径是否正确:

print(os.getcwd())

安卓Pydroid3环境下默认可写目录为/data/user/0/ru.iiec.pydroid3/files/,你可以把parent_dir改成该目录下的子路径,确保有写入权限。

内容的提问来源于stack exchange,提问作者TutorialWarrior 9776

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 10:00:05