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?
do_the_thing_*methods? Because your exception usage is always effectively ignoring it, so to me it feels like you can go foros.path.isfile()oros.path.exists()in an if condition. This question seems to have a lot of such approaches. If you are immediately opening the file inside those methods, maybe consider putting the try-except inside that method?os.path.isfile()?try-exceptinside the various methods, having it try one of the various approaches to check for file existence as the first step and encapsulating the entire rest of the method in thetryblock? Various methods are just data cleaning and processing - first step is opening the file, last step is re-saving it - so I think something like that would work, but could you give an example?if file_exists:(using one of the variousosmethods), and maybeelse: report_file_missing?