English 中文(简体)
1. 在“工业”经营者中“为” lo
原标题:Nesting "for" loop within a "try" operator

Folks,

我已辞去了自己在这个问题上的工作,但我想检查一下是否真的按预期行事。

In the example, "sample.txt" is any multi-line text file that is read and parsed.

try:
    file=open( sample.txt , r )
    for line in file:
          (some action here)
except:
    print "Couldn t open file"
file.close()

我观察到的行动是,“mple.txt”是开放的,第1行处理,逻辑随后是“除外”条款。

WAD or is this a bug?

问题回答

如果“<>条码>除外的代码运行,是因为提出了例外。 你掩盖了例外情况,使人难以知道什么是错的。

你的错误信息表明,你正在试图将档案中产生的错误固定下来。 但是,由于您的<代码>try的栏目围绕整个档案处理,处理过程中提出的例外情况,而不是公开的档案,将被误报为“不应公开档案”。 如果你真的必须处理这一例外情况,那么你就必须将<>条码>移至<>条码>之后。

Personally I d be inclined to simply ignore the exception and let the default handling of the exception halt execution:

with open( sample.txt , r ) as file:
    for line in file:
        (some action here)

如果你必须处理例外情形,那么就会发现你处理的特殊类别。 例如,仅处理<代码>IOError。 既然如此,如果出现故障,就会提出<条码>开放<>。

try:   
    with open( sample.txt , r ) as file:
        for line in file:
            (some action here)
except IOError:
    except IOError as (errno, strerror):
        print "I/O error({0}): {1}".format(errno, strerror)

然后,它没有在<代码>开放<>/代码>线上失效。 什么是例外?

try:
    file=open( sample.txt , r )
    for line in file:
          (some action here)
except:
    print "Exception:"
    import traceback; traceback.print_exc()

file.close()

That bare except catches all exceptions, including ones in the (some action here) part. Restructure that as:

try:
    inputfile = open( sample.txt ,  r )
except:
    print "Couldn t open file"
else:
    for line in inputfile: pass
    inputfile.close()

甚至更好:

with open( sample.txt ,  r ) as inputfile:
    for line in inputfile: pass

总的来说,在<条码>栏>内只列出最低限度的代码。 block,以便你不再偶然处理例外,否则你真的不愿意处理。

your code risks raising another assertion trying to close file if for some reason the open() call fails. This is because the file variable won t be set if open() raises an exception, and so your call further down will reference a variable that doesn t exist.

如有可能,利用声明:

with open( sample.txt ,  r ) as file:
    try:
        for line in file:
            (some action)
    except:
        print "Exception"
        import traceback; traceback.print_exc()

这将确保案卷随后结案,而不论在案卷中发生什么情况。

利用阅读线制作档案中所有内容的清单。 并且,你也无意在不至少印刷错误代码的情况下追捕一般错误。

try:
    file=open( sample.txt , r )
    for line in file.readlines():
          (some action here)
except Exception, e:
    print str(e)
file.close()

The actions I observe are that "sample.txt" is opened and the first line handled, the logic then falls through to the "except" clause.

是的,情况就是这样。 但只要档案存在,这只是

As for the error falling through to the except clause (assuming the file exists), that implies that there is an issue with the parsing logic you ve implemented. We can t be sure what it is since the except catches everything, and unless it s re-raised (may as well not catch it then...), or you print the stack trace from the exception object, you can t tell what is going wrong or where. In general, this is why catching everything is frowned upon; it makes debugging unnecessarily difficult.

我还注意到,你正在最后结案。 这可能是另一个错误来源,因为该档案只在<条码>范围内存在。 你有两种选择:

  1. Include file.close() inside of your try block so the file is properly closed after you re done, or
  2. Use the with statement as a context manager to automatically close the file when you re done. @David Heffernan s example is one that s similar to one I would write.




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...