尝试读取文件的 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 = {}
对于两个文件,我认为这种方法已经足够好了。
如果您有更多文件要回退,我会使用循环:
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 = {}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句