尝试读取文件的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 = {}
答案 0 :(得分:1)
对于两个文件,这种方法在我看来足够好。
如果你有更多的文件需要后备,我会选择循环:
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 = {}
答案 1 :(得分:0)
您可以先检查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'
答案 2 :(得分:0)
虽然我不确定这是否是pythonic,但也许是这样的:
file_to_open = file1 if os.path.isfile(file1) else file2