如何正确引发 FileNotFoundError?

我使用第三方库,这很好,但不处理不存在的文件的方式,我想。当给它一个不存在的文件,而不是提出好的老

FileNotFoundError: [Errno 2] No such file or directory: 'nothing.txt'

它传递出一些模糊的信息:

OSError: Syntax error in file None (line 1)

我不想处理丢失的文件,不想捕获或处理异常,不想引发自定义异常,既不想我 open的文件,也不想创建它,如果它不存在。

我只想检查它是否存在(os.path.isfile(filename)可以做到这一点) ,如果不存在,那么只需引发一个适当的 FileNotFoundError。

我试过了:

#!/usr/bin/env python3


import os


if not os.path.isfile("nothing.txt"):
raise FileNotFoundError

什么只有输出:

Traceback (most recent call last):
File "./test_script.py", line 6, in <module>
raise FileNotFoundError
FileNotFoundError

这比“文件 Nothing 中的语法错误”要好,但是如何使用正确的消息引发“真正的”python 异常,而不必重新实现它呢?

88299 次浏览

Pass in arguments:

import errno
import os


raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), filename)

FileNotFoundError is a subclass of OSError, which takes several arguments. The first is an error code from the errno module (file not found is always errno.ENOENT), the second the error message (use os.strerror() to obtain this), and pass in the filename as the 3rd.

The final string representation used in a traceback is built from those arguments:

>>> print(FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), 'foobar'))
[Errno 2] No such file or directory: 'foobar'

In Python, a variable can refer to the type (class), or an object (instance of the class):

>>> x = FileNotFoundError
>>> print(type(x))
<class 'type'>


>>> x = FileNotFoundError()
>>> print(type(x))
<class 'FileNotFoundError'>

While it's possible to also throw the type FileNotFoundError, you practically always want to throw an object that has been constructed from the class. The constructor accepts the same arguments as OSError. You can pass a standard POSIX and Windows error code, but it's enough to pass an error message. (In your case the standard error message "No such file or directory" is not entirely accurate, since you also throw the error if a directory is found.)

if not os.path.isfile("nothing.txt"):
raise FileNotFoundError("nothing.txt was not found or is a directory")