【发布时间】:2017-08-30 08:25:57
【问题描述】:
尝试读取文件的 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 = {}
【问题讨论】:
标签: python exception-handling try-except