Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 778
user2736211 Avatar asked Aug 31 '13 20:08

user2736211


People also ask

How do you save the output of a Python program in a text file?

First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

How do you create a text file in Python?

Summary. Use the function open(“filename”,”w+”) for Python create text file. The + tells the python interpreter for Python open text file with read and write permissions. Use the readlines function to read the content of the file one by one.


1 Answers

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']
like image 172
blakev Avatar answered Sep 22 '22 09:09

blakev