Home  >  Q&A  >  body text

python - [Errno 2] No such file or directory: '我为什么是一个文件,为什么返回值是这样的呢?

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

大家讲道理大家讲道理2740 days ago755

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-18 10:21:03

    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

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:21:03

    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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:21:03

    Modify it like this,
    This is IOError

    reply
    0
  • Cancelreply