2

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
magicsword
  • 1,179
  • 3
  • 16
  • 26

2 Answers2

5

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'
Craig
  • 4,605
  • 1
  • 18
  • 28
  • 1
    I like this except how about `OSError`? – tdelaney Oct 06 '20 at 23:45
  • This is good. I have several files so this will do the Job. – magicsword Oct 06 '20 at 23:46
  • @tdelaney As in, try to open the file and it will raise `OSError` automatically, or raise `OSError` instead of a generic exception? I was following the OP's pattern assuming that they had a reason for raising a generic exception. – Craig Oct 06 '20 at 23:47
  • 3
    @Craig, since a generic `Exception` is almost always a bad idea, I thought it would be nice if your example fixed it. – tdelaney Oct 06 '20 at 23:50
3

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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Fedor Soldatkin
  • 1,133
  • 8
  • 23