Python: How do I save generator output into text file?
Asked Answered
U

2

15

I am using the following generator to calculate a moving average:

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)

I can print the generator output, but I can't figure out how to save that output into a text file.

x = (1,2,2,4,1,3)
avg = moving_average(x,2)
for value in avg:
    print value

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.

Thanks in advance.

Unnerve answered 31/8, 2013 at 20:56 Comment(1)
C
21
def generator(howmany):
    for x in xrange(howmany):
        yield x

g = generator(10)

with open('output.txt', 'w') as f:
    for x in g:
        f.write(str(x))

with open('output.txt', 'r') as f:
    print f.readlines()

output:

>>> 
['0123456789']
Chantey answered 31/8, 2013 at 21:3 Comment(2)
Thanks! I just needed to change the generator output to a string to write to a text file. I wanted to keep the numbers in column format so I added a line ending: f.write(str(x)+'\n').Unnerve
If you need to write exactly the strings from the generator output, you could just use f.writelines(g)Liberality
G
1

Since you are using a generator, you can use file.writelines(), which writes an iterable of strings to a file.

You may want to combine your generator with a line generator, to do string conversion and add newlines.

from collections.abc import Iterator
from os import linesep
from sys import stdout

def generator(n: int) -> int:
    for x in range(n):
        yield x

def line_generator(iterable) -> Iterator[str]:
    """Takes an iterable and generates lines"""
    for x in iterable:
        yield str(x)  # Convert to string
        yield linesep # Bring your own line-endings

stdout.writelines(line_generator(generator(10)))
Gebler answered 7/2 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.