使用丢失的文件名引发异常

mag*_*ord 2 python

我想用丢失的文件名引发异常:

f1 = Path(DIR_PATH, "one.txt").resolve()
f2 = Path(DIR_PATH, "two.txt").resolve()

# 1 Is there a way of doing this?
if not f1.exists() or not f2.exists():
    raise Exception(f"The file {?} does not exist")

# 2 instead of this
if not f1.exists():
    raise Exception(f"The file {f1} does not exist")
elif not f2.exists():
    raise Exception(f"The file {f2} does not exist")
Run Code Online (Sandbox Code Playgroud)

有没有办法从上面的代码中做#1而不是#2?

Cra*_*aig 5

您可以对文件运行循环:

for fn in [f1, f2]:
    if not fn.exists():
        raise Exception(f"The file {fn} does not exist")
Run Code Online (Sandbox Code Playgroud)

对于只有两个文件,这比您的选项 #2 短一行,但如果您有更多文件,这将比一系列if语句更紧凑。

正如@tdelaney 所指出的,最好提出一个特定的错误,而不是使用通用的Exception. 一个更合适的方法是OSError,如Martjin Peters 的这个回答中所解释的那样,它使用许多参数来调用:

import os
import errno

for fn in [f1, f2]:
    if not fn.exists():
        raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), fn)
Run Code Online (Sandbox Code Playgroud)

指定错误代码errno.ENOENT,将引发 的FileNotFoundError子类OSError,如果您试图打开一个不存在的文件,您会得到同样的错误。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'one.txt'
Run Code Online (Sandbox Code Playgroud)

  • @Craig,由于通用的“异常”几乎总是一个坏主意,我认为如果你的示例修复它会很好。 (3认同)