我正在使用Python 2.5。我试图用这个'with'语句。与迭代器使用python'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.read()
取代f.next()
,它似乎陷入了无限循环。
我想知道是否必须编写一个接受迭代器对象作为参数的装饰器类,并为其定义一个__exit__
方法?
我知道这是更Python使用一个for循环的迭代器,但我想实现一个,用一个for循环...什么like
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)
与'with' ...无关吗? – stefanB 2010-03-12 04:29:51
是的,显得如此。我认为'with'语句为异常处理提供了一种替代形式,但我想不是这样。 – hatmatrix 2010-03-12 04:36:57
请更新标题。 – 2010-03-12 11:37:39