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



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

这是我编写的示例代码,它使用嵌套的try-except块。这是蟒蛇吗:

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

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

如果你有更多的文件要备份,我会使用一个循环:

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

您可以先检查file1是否存在,然后决定打开哪个文件。它将缩短代码并避免重复try -- catch子句。我认为它更像Python,但请注意,您需要在模块中使用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'

虽然我不确定这是否是蟒蛇,但可能是类似于:

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

我建议使用pathlib.Path

from pathlib import Path
path1 = Path(file1)
path2 = Path(file2)
path = path1 if path1.exists() else path2
with path.open('r') as f:
params = json.load(f)

如果需要,您可以添加额外的错误检查path2是否存在。

最新更新