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

Python代码报错NameError: name 'OError' is not defined,如何解决?

错误排查与修正

你的代码存在两个明确问题:

  • 异常类拼写错误:你写的OError并非Python内置异常类,正确的类名是OSError,这正是触发NameError的直接原因。
  • 文件打开模式错误:你用"r"(只读模式)打开文件,却尝试调用write()方法写入内容,这会触发io.UnsupportedOperation异常——只读模式不支持写入操作。

修正后的代码示例:

try:
    # 用写入模式"w"打开文件,文件不存在则创建,存在则清空原有内容
    # 若要追加内容可改用"a"模式
    fh = open("testfile", "w")
    fh.write("this is my test file for exception handling!!")
except OSError:
    print("Error: can't find file or read data")
else:
    print("content written successfully")
    fh.close()  # 建议手动关闭文件,或使用with语句更安全

更推荐使用with语句管理文件,它会自动帮你关闭文件,避免资源泄漏:

try:
    with open("testfile", "w") as fh:
        fh.write("this is my test file for exception handling!!")
except OSError:
    print("Error: can't find file or read data")
else:
    print("content written successfully")

内容的提问来源于stack exchange,提问作者Javed Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:15:34