【问题标题】:Pythonic way to try reading a file and in case of exception fallback to alternate file尝试读取文件并在异常情况下回退到备用文件的 Pythonic 方式
【发布时间】: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


    【解决方案1】:

    对于两个文件,我认为这种方法已经足够好了。

    如果您有更多文件要回退,我会使用循环:

    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 = {}
    

    【讨论】:

      【解决方案2】:

      您可以先检查file1是否存在,然后再决定打开哪个文件。它将缩短代码并避免重复 try -- catch 子句。我相信它更 Pythonic,但请注意,您需要在模块中使用 import os 才能使其正常工作。 可以是这样的:

      fp = file1 if os.path.isfile(file1) else file2
      if os.path.isfile(fp):
          try:
              with open(fp, "r") as f:
                  params = json.load(f)
          except Exception as exc:
              print("Error reading config file {}: {}".format(fp, str(exc)))
                  params = {}
      else:
          print 'no config file'
      

      【讨论】:

      • 这可能会导致竞争条件,另外OSError 也可能是由于PermissionError 等造成的。
      • 如果你在没有适当权限的情况下尝试open(fp, "r"),你不会得到PermissionError吗?
      【解决方案3】:

      虽然我不确定这是否是pythonic,但可能是这样的:

      file_to_open = file1 if os.path.isfile(file1) else file2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-01
        • 2012-05-24
        • 1970-01-01
        • 1970-01-01
        • 2011-12-21
        • 2011-05-18
        • 1970-01-01
        相关资源
        最近更新 更多