python - [Errno 2] No such file or directory: '我为什么是一个文件,为什么返回值是这样的呢?
大家讲道理
大家讲道理 2017-04-18 10:19:03
0
3
760

try:
    f=open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错了n错误的原因是:'+str(reason))
文件出错了
错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件

如果不加as reason返回的就是

try:
    f=open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError:                      #ose要大写 才能有正确报错
    print('文件出错了')
文件出错了

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

Antworte allen(3)
迷茫

OSError是python内置异常,python变量是区分大小写的
参见https://docs.python.org/2/lib...

另外文件不存在的话,你啥都不写的话,只写except也是会报错的

黄舟

except OSError as reason => 捕获OSError异常, 并且赋值给reason, 所以你在print('文件出错了n错误的原因是:'+str(reason)) 就将是触发异常的原因拼接成一句完整的错误 就是说执行try 没执行成功的话就执行except

巴扎黑

这样修改,
这个是IOError

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!