从两个文件路径之一加载数据的最干净和 pythonic 的方法是什么?为什么我无法捕获两个相同的异常?



我有两个潜在的文件路径,我的应用程序可以从中读取特定数据。如果一个失败了,我希望它从另一个读取。

我这样做的直觉尝试是尝试...除子句外,具有以下内容:

# Try the first file path
try:
file = open(possible_path_1)
content = file.read()
# File is not in first location, try the second
except IOError:
file = open(possible_path_2)
content = file.read()
# Could not read from either location, throw custom CriticalException
except IOError:
raise CriticalException("Could not read the file!")

但是,这似乎并不像直觉预期的那样工作。第二个IOError永远不会被捕获。为什么会这样呢?是否有任何"干净"的方法可以从一个文件路径或另一个文件路径读取而无需手动检查os.path.exists(filepath) and os.path.isfile(filepath)

这是一个替代方案,但不确定它是否"更漂亮":

for path in paths:
try:
file = open(path)
content = file.read()
# File is not in first location, try the second
except IOError:
continue
break
else: # for-else gets executed if break never happens
raise CriticalException("Could not read the file!")

假设您在某个容器中拥有所有可能的路径,paths

虽然老实说,我根本不会在这里使用异常处理,但我认为这更清楚(当然,我会使用pathlib而不是os.path

from pathlib import Path
for path in map(Path, paths):
if path.exists():
content = path.read_text()
break
else:
raise CriticalException("Could not read the file!")

最新更新