title: using python 'with' statement with iterators?
body: <p>I'm using Python 2.5. I'm trying to use this 'with' statement.</p>
  
  <pre><code>from __future__ import with_statement
  a = []
  with open('exampletxt.txt','r') as f:
      while True:
          a.append(f.next().strip().split())
  print a
  </code></pre>
  
  <p>The contents of 'exampletxt.txt' are simple:</p>
  
  <pre><code>a
  b
  </code></pre>
  
  <p>In this case, I get the error:</p>
  
  <pre><code>Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "/tmp/python-7036sVf.py", line 5, in &lt;module&gt;
      a.append(f.next().strip().split())
  StopIteration
  </code></pre>
  
  <p>And if I replace <code>f.next()</code> with <code>f.read()</code>, it seems to be caught in an infinite loop.</p>
  
  <p>I wonder if I have to write a decorator class that accepts the iterator object as an argument, and define an <code>__exit__</code> method for it?</p>
  
  <p>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 <a href="https://stackoverflow.com/questions/2264504/processing-text-from-a-non-flat-file-to-extract-information-as-if-it-were-a-fl">like</a></p>
  
  <pre><code>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)
  </code></pre>