在迭代器中使用Python的'with'语句?

3 投票
4 回答
1793 浏览
提问于 2025-04-15 20:20

我正在使用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

如果我把 f.next() 替换成 f.read(),似乎就会陷入一个无限循环。

我在想,是否需要写一个装饰器类,接受迭代器对象作为参数,并为它定义一个 __exit__ 方法呢?

我知道对于迭代器来说,使用for循环更符合Python的风格,但我想在一个生成器中实现一个while循环,然后再用for循环来调用它……就像这样

def g(f):
    while True:
        x = f.next()
        if test1(x):
            a = x
        elif test2(x):
            b = f.next()
            yield [a,x,b]

a = []
with open(filename) as f:
    for x in g(f):
        a.append(x)

4 个回答

1

你的 while 循环里没有任何结束的条件,这样你就一直在执行,直到出现 StopIteration 异常,而你又没有处理这个异常。

1

你的 while 循环一直在运行,但文件已经结束了,所以当没有更多内容可以读取时,就会出现一个叫做 StopIteration 的错误。

3

当一个迭代器走到最后时,它会抛出一个叫做 StopIteration 的信号。通常情况下,for 循环会默默地捕捉到这个信号,然后继续执行 else 部分。但是如果你是手动去遍历这个迭代器,就需要在代码中准备好处理这个信号的情况。

撰写回答