Search code examples
pythonexceptiontry-except

Pythonic way to try reading a file and in case of exception fallback to alternate file


What is the Pythonic way to try reading a file and if this read throws an exception fallback to read an alternate file?

This is the sample code I wrote, which uses nested try-except blocks. Is this pythonic:

try:
    with open(file1, "r") as f:
        params = json.load(f)
except IOError:
    try:
        with open(file2, "r") as f:
            params = json.load(f)
    except Exception as exc:
        print("Error reading config file {}: {}".format(file2, str(exc)))
        params = {}
except Exception as exc:
    print("Error reading config file {}: {}".format(file1, str(exc)))
    params = {}

Solution

  • For two files the approach is in my opinion good enough.

    If you had more files to fallback I would go with a loop:

    for filename in (file1, file2):
        try:
            with open(filename, "r") as fin:
                params = json.load(f)
            break
        except IOError:
            pass
        except Exception as exc:
            print("Error reading config file {}: {}".format(filename, str(exc)))
            params = {}
            break
    else:   # else is executed if the loop wasn't terminated by break
        print("Couldn't open any file")
        params = {}