I am using Python 2.5. I am trying to use this expression with.
from __future__ import with_statement a = [] with open('exampletxt.txt','r') as f: while True: a.append(f.next().strip().split()) print a
The contents of "exampletxt.txt" is simple:
a b
In this case, I get the error:
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
And if I replaced f.next() with f.read() , it seems to end up in an infinite loop.
I wonder if I should write a decorator class that takes an iterator object as an argument and define an __exit__ method for it?
I know that it is more pythonic to use for-loop for iterators, but I wanted to implement a while loop in the generator that called the for ... loop something
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)
source share