尝试读取文件并在异常回退到备用文件的情况下使用 Pythonic 方法

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

尝试读取文件的 Pythonic 方法是什么,如果此读取抛出异常回退以读取备用文件?

这是我写的示例代码,它使用嵌套的 try-except 块。这是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 = {}

您可以先检查file1是否存在,再决定打开哪个文件。它将缩短代码并避免重复 try -- catch 子句。我相信它更像 pythonic,但是请注意,您需要在模块中 import os 才能正常工作。 它可以是这样的:

fp = file1 if os.path.isfile(file1) else file2
if os.path.isfile(fp):
    try:
        with open(fp, "r") as f:
            params = json.load(f)
    except Exception as exc:
        print("Error reading config file {}: {}".format(fp, str(exc)))
            params = {}
else:
    print 'no config file'

虽然我不确定这是否是 pythonic 的,也许是这样的:

file_to_open = file1 if os.path.isfile(file1) else file2

对于两个文件,我认为该方法已经足够好了。

如果您有更多文件要后备,我会循环使用:

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 = {}