Pythonic方法尝试读取文件,并在出现异常时回退到备用文件

Pythonic方法尝试读取文件,并在出现异常时回退到备用文件,python,exception-handling,try-except,Python,Exception Handling,Try Except,尝试读取文件的Pythonic方法是什么?如果此读取引发异常,则回退以读取备用文件 这是我编写的示例代码,它使用嵌套的try-块,但块除外。这是蟒蛇式的吗 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

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

这是我编写的示例代码,它使用嵌套的
try
-
块,但
块除外。这是蟒蛇式的吗

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

您可以先检查文件1是否存在,然后决定打开哪个文件。它将缩短代码并避免重复
try--catch
子句。我相信它更像python,但是请注意,您需要
在模块中导入操作系统
,这样才能工作。 它可以是这样的:

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'
file_to_open = file1 if os.path.isfile(file1) else file2

虽然我不确定这是否是肾盂型的,但可能类似于:

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

这可能会导致竞争条件,加上
OSError
也可能是由于
PermissionError
等原因造成的。如果您在没有适当权限的情况下尝试
open(fp,“r”)
,您不会得到
PermissionError