def generator(howmany):
    for x in range(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:
    pass
Python: How do I save generator output into text file?