【问题标题】:What's the most clean and pythonic way to load data from one of two file paths? Why can't I catch two of the same Exceptions?从两个文件路径之一加载数据的最干净和最pythonic的方法是什么?为什么我不能捕获两个相同的异常?
【发布时间】: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


【解决方案1】:

这是另一种选择,但不确定它是否“更漂亮”:

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!")

【讨论】:

  • 我更喜欢这个。 for 之后的 else 声明...永远不知道。干杯伙伴!
  • 不应该在if path.exists() 子句内休息吗?
  • @Dalofeco 是的,错字
猜你喜欢
  • 1970-01-01
  • 2017-02-08
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
相关资源
最近更新 更多