最佳答案
我使用第三方库,这很好,但不处理不存在的文件的方式,我想。当给它一个不存在的文件,而不是提出好的老
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 异常,而不必重新实现它呢?