raise an exception with the name of the file that is missing

Viewed 271

I want to raise an exception with the name of the file that is missing:

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")

Is there a way of doing #1 rather than #2 from the above code?

2 Answers

You could run a loop over the files:

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

For only two files, this is one line shorter than your option #2, but if you have more files this will be much more compact than a series of if statements.

As pointed out by @tdelaney, it would be better to raise a specific error instead of using the generic Exception. A more appropriate one is OSError, which is called with a number of arguments as explained in this answer from Martjin Peters:

import os
import errno

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

Specifying the error code errno.ENOENT, will raise the FileNotFoundError subclass of OSError, the same error you would get if you tried to open a non-existent file.

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

No, there is no way to implicitly determine which proposition in disjunction is True.

Related