I have a set of slightly different operations I want to perform on a bunch of different files, some of which may or may not exist at any given time. In all cases, if a file doesn't exist (returning FileNotFoundError
), I want it to just log that that particular file doesn't exist, then move on, i.e. identical exception handling for all FileNotFoundError
cases.
The tricky part is that what I want to do with each set of file is slightly different. So I can't simply do:
for f in [f1, f2, f3, f4]:
try:
do_the_thing(f)
except FileNotFoundError:
print(f'{f} not found, moving on!')
Instead I want something like:
try:
for f in [f_list_1]:
do_thing_A(f)
for f in [f_list_2]:
do_thing_B(f)
for f in [f_list_3]:
do_thing_C(f)
except FileNotFoundError:
print(f'{f} not found, moving on!')
But where each for
block is tried regardless of success / failure of previous block.
Obviously I could use a whole lot of separate try
-except
sets:
for f in [f_list_1]:
try:
do_thing_A(f)
except FileNotFoundError:
print(f'{f} not found, moving on!')
for f in [f_list_2]:
try:
do_thing_B(f)
except FileNotFoundError:
print(f'{f} not found, moving on!')
for f in [f_list_3]:
try:
do_thing_C(f)
except FileNotFoundError:
print(f'{f} not found, moving on!')
But is there a more elegant or Pythonic way to do this, given that it's the same exception handling in each case?