开发者社区> 问答> 正文

python中读取文件异常没有被捕获

try:
    fh = open("testfile", "r")
    fh.write("这是一个测试文件,用于测试异常!!")
except FileExistsError:
    print("Error: 没有找到文件或读取文件失败")

运行报错

Traceback (most recent call last):
  File "/Users/jiangyd/PycharmProjects/untitled16/b.py", line 48, in <module>
    fh.write("这是一个测试文件,用于测试异常!!")
io.UnsupportedOperation: not writable

展开
收起
水果黄瓜 2021-10-24 10:55:34 563 0
1 条回答
写回答
取消 提交回答
  • 这是因为文件模式r是不支持的,可以改成其他的,例如a

    try:
        fh = open("testfile", "a")
        fh.write("这是一个测试文件,用于测试异常!!")
    except FileExistsError:
        print("Error: 没有找到文件或读取文件失败")
    
    2021-10-25 21:31:03
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载