using python 'with' statement with iterators?
Posted
by Stephen
on Stack Overflow
See other posts from Stack Overflow
or by Stephen
Published on 2010-03-12T04:24:48Z
Indexed on
2010/03/15
2:19 UTC
Read the original article
Hit count: 466
python
Hi, I'm using Python 2.5. I'm trying to use this 'with' statement.
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' are 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 replace f.next()
with f.read()
, it seems to be caught in an infinite loop.
I wonder if I have to write a decorator class that accepts the iterator object as an argument, and define an __exit__
method for it?
I know it's more pythonic to use a for-loop for iterators, but I wanted to implement a while loop within a generator that's called by a for-loop... something 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)
© Stack Overflow or respective owner