使用python';与';带迭代器的语句?

使用python';与';带迭代器的语句?,python,Python,我正在使用Python 2.5。我试着用这个“with”语句 from __future__ import with_statement a = [] with open('exampletxt.txt','r') as f: while True: a.append(f.next().strip().split()) print a “exampletxt.txt”的内容很简单: a b 在这种情况下,我得到错误: Traceback (most recent ca

我正在使用Python 2.5。我试着用这个“with”语句

from __future__ import with_statement
a = []
with open('exampletxt.txt','r') as f:
    while True:
        a.append(f.next().strip().split())
print a
“exampletxt.txt”的内容很简单:

a
b
在这种情况下,我得到错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/python-7036sVf.py", line 5, in <module>
    a.append(f.next().strip().split())
StopIteration

提升
StopIteration
是迭代器在结束时所做的事情。通常情况下,
for
语句以静默方式捕获它并继续执行
else
子句,但是如果它像您的情况一样被手动迭代,那么代码必须准备好处理异常本身。

您的while循环不会结束,但是该文件会这样做,当没有其他可迭代的对象时,它会引发StopIteration异常。

在任何while循环中都没有任何终止条件,因此您会一直返回,直到您得到StopIteration异常,而您无法处理该异常。

在使用显式下一个循环时,始终可以重写。当您有一个显式的
next
时,您只需向前看一个令牌

通常,这种形式的循环可以重写

def g(f):
    while True:
        x = f.next()
        if test1(x):
            a = x
        elif test2(x):
            b = f.next()
            yield [a,x,b]
您始终可以通过缓冲一个值来替换前瞻
next

def g(f):
    prev, a = None, None
    for x in f:
        if test2(prev)
            yield [ a, prev, x ]
        elif test1(x):
            a = x
        prev= x

无关?是的,看起来是这样。我认为“with”语句为异常处理提供了另一种形式,但我想不是这样。请更新标题。谢谢,但这确实是with语句在本例中的适用性问题。谢谢。我想我认为“with”语句也应该处理该异常,但我想不是…谢谢-看起来for循环是处理这些迭代器的方法。
def g(f):
    prev, a = None, None
    for x in f:
        if test2(prev)
            yield [ a, prev, x ]
        elif test1(x):
            a = x
        prev= x