I was trying the following list comprehension:
dirpaths = [x for x in datadir.iterdir() if x.is_dir()]
where I got an OSError due to some network access “[WinError 59] An unexpected network error occurred”. As I don’t care about the directories I don’t have access to, I wonder how I could ignore an exception within a list comprehension and avoid having to write a for-loop with a try/except block:
dirpaths = []
for path in datadir.iterdir():
try:
is_dir = path.is_dir()
except OSError:
continue
if is_dir:
dirpaths.append(path)
I tried looking for other ideas in the discussion board, but couldn’t find anything relevant. One idea I had was possibly introducing an except as an inline operator.
dirpaths = [x for x in datadir.iterdir() if x.is_dir() except False]
This would follow a similar pattern as the or operator, but would handle exceptions raised by the preceding expression:
a = 0 or 5
a = foo() except 5
One drawback is that you wouldn’t be able to specify a specific type of exception.
Philippe