title: Python: How do I save generator output into text file?
body: <p>I am using the following generator to calculate a moving average:</p>
  
  <pre><code>import itertools
  from collections import deque
      def moving_average(iterable, n=50):
      it = iter(iterable)
      d = deque(itertools.islice(it, n-1))
      d.appendleft(0)
      s = sum(d)
      for elem in it:
          s += elem - d.popleft()
          d.append(elem)
          yield s / float(n)
  </code></pre>
  
  <p>I can print the generator output, but I can't figure out how to save that output into a text file.</p>
  
  <pre><code>x = (1,2,2,4,1,3)
  avg = moving_average(x,2)
  for value in avg:
      print value
  </code></pre>
  
  <p>When I change the print line to write to a file, output is printed to the screen, a file is created but it stays empty.</p>
  
  <p>Thanks in advance.</p>