【问题标题】:Confused about the proper order of try and with in Python对 Python 中 try 和 with 的正确顺序感到困惑
【发布时间】:2014-04-23 09:46:40
【问题描述】:

我在这里读到建议使用with open(filename) 而不是使用open(filename) 和filename.close() 对(至少对于基本任务),并且最好使用try。

Q1:如果我的理解是正确的,正确的顺序是什么?

try:
  with open(filename) as f:
    do something, eg. match string

或

with open(filename) as f:
  try:
    do something, eg. match string

Q2:如果我还想插入一些代码来弹出文件处理错误的弹出窗口,哪种情况更好? (对于未找到的文件,或其他)

【问题讨论】:

    标签: python try-catch with-statement contextmanager


    【解决方案1】:

    让您的try / except 语句尽可能靠近异常源。

    如果您没有捕捉到IOErrors,请将其放在with 语句中。另一方面,如果open() 抛出异常,请将其围绕 with 语句。

    如果with 语句较长,或者您不想掩盖with 语句套件中引发的相同异常,请执行open() 调用首先:

    try:
        fileobj = open(filename)
    except IOError:
        print('File problems!')
    else:
        with fileobj as f:
            # do something
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-18
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2014-07-29
      • 1970-01-01
      相关资源
      最近更新 更多