【发布时间】:2019-08-16 04:04:40
【问题描述】:
我有两个潜在的文件路径,我的应用程序可以从中读取特定数据。如果一个失败,我希望它从另一个读取。
我的直觉尝试是使用 try...except 子句,如下所示:
# 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)?
【问题讨论】:
-
因为您需要将第一个
except子句中的内容包装在 another try-except 中,这个嵌套在其中。不是第三个子句 -
我知道我可以做到这一点,但它太丑陋了。我拒绝这样做,并想知道是否有更清洁的选择。也许我在问乌托邦代码......
-
好吧,玩得开心。你基本上是在要求一个
if-elif-else构造,除了异常处理 -
为什么不遍历路径,比如
for path in possible_paths: try:...? -
这是个好建议。如果文件被正确读取,可能最终会这样做,并添加
break。
标签: python file exception error-handling