本文介绍了如何从Python 3导入FileNotFoundError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前在需要Python 3内置异常的项目上使用Python 2: FileNotFoundError 。我该怎么做?

I am currently using Python 2 on a project that needs a Python 3 built-in exception: FileNotFoundError. How do I do it?

推荐答案

您当然可以定义所需的任何异常。

You can of course define any exceptions you want.

但是他们不会对你有任何好处。 FileNotFoundError 的全部要点是,任何遇到找不到文件的错误的Python操作都会引发该异常。仅定义自己的例外并不能实现。您将得到的是带有相应内容的 OSError (或 IOError ,具体取决于2.x版本) errno 的值。如果您尝试处理自定义 FileNotFoundError ,则永远不会调用您的处理程序。

But they're not going to do you any good. The whole point of FileNotFoundError is that any Python operation that runs into a file-not-found error will raise that exception. Just defining your own exception won't make that true. All you're going to get is an OSError (or IOError, depending on 2.x version) with an appropriate errno value. If you try to handle a custom FileNotFoundError, your handler will never get called.

所以,您真正想要的是什么例如:

So, what you really want is (for example):

try:
    f = open(path)
except OSError as e:
    if e.errno == errno.ENOENT:
        # do your FileNotFoundError code here
    else:
        raise

这篇关于如何从Python 3导入FileNotFoundError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:24