python 'with' statement

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/12 4:27 UTC
Read the original article Hit count: 348

Filed under:

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 test(x):
            a = x
        elif test(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

Related posts about python