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