Python 如何正确引发 FileNotFoundError?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36077266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I raise a FileNotFoundError properly?
提问by zezollo
I use a third-party library that's fine but does not handle inexistant files the way I would like. When giving it a non-existant file, instead of raising the good old
我使用了一个很好的第三方库,但没有按照我想要的方式处理不存在的文件。当给它一个不存在的文件时,而不是提高旧的
FileNotFoundError: [Errno 2] No such file or directory: 'nothing.txt'
it raises some obscure message:
它提出了一些晦涩的信息:
OSError: Syntax error in file None (line 1)
I don't want to handle the missing file, don't want to catch nor handle the exception, don't want to raise a custom exception, neither want I to open
the file, nor to create it if it does not exist.
我不想处理丢失的文件,不想捕获或处理异常,不想引发自定义异常,既不想open
文件,也不想在文件不存在时创建它。
I only want to check it exists (os.path.isfile(filename)
will do the trick) and if not, then just raise a proper FileNotFoundError.
我只想检查它是否存在(os.path.isfile(filename)
会解决问题),如果不存在,那么就提出一个正确的 FileNotFoundError。
I tried this:
我试过这个:
#!/usr/bin/env python3
import os
if not os.path.isfile("nothing.txt"):
raise FileNotFoundError
what only outputs:
只输出什么:
Traceback (most recent call last):
File "./test_script.py", line 6, in <module>
raise FileNotFoundError
FileNotFoundError
This is better than a "Syntax error in file None", but how is it possible to raise the "real" python exception with the proper message, without having to reimplement it?
这比“文件 None 中的语法错误”要好,但是如何用正确的消息引发“真正的”python 异常,而不必重新实现它?
回答by Martijn Pieters
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.
FileNotFoundError
是 的子类OSError
,它接受多个参数。第一个是来自errno
模块的错误代码(找不到文件总是errno.ENOENT
),第二个是错误消息(用于os.strerror()
获取此信息),并将文件名作为第三个传入。
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'