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

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('文件出错了')
文件出错了

大家讲道理
大家讲道理

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

reply all(3)
迷茫

OSError is a built-in exception in python, python variables are case-sensitive
See https://docs.python.org/2/lib...

In addition, if the file does not exist, if you write nothing and just write except, an error will be reported

黄舟

except OSError as reason => Capture the OSError exception and assign it to reason, so when you print('The file has an error and the reason for the error is:'+str(reason)), you will splice the reason for triggering the exception into a complete sentence The error means executing try. If the execution fails, execute except

巴扎黑

Modify it like this,
This is IOError

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template