Python Forum
Write stdout to file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Write stdout to file (/thread-1410.html)



Write stdout to file - mcmxl22 - Dec-31-2016

I need the lines() function to write the results of a = [int(x) for x in str(i)] to fibo.txt but it's coming up empty.
I have tried taking the f.write() out of the for loop but it has the same results. Do I need a separate function for f.write()

def F():
    a, b = 0, 1
    yield a
    yield b
    while True:
        a, b = b, a + b
        yield b


def subfib(StartNumber, endNumber):
    for cur in F():
        if cur > endNumber:
            return
        if cur >= StartNumber:
            yield cur

def lines():
    for i in subfib(2, 400):
        a = [int(x) for x in str(i)]

        with open('fibo.txt', 'w') as f:
            f.write(a)
f.close()

lines()



RE: Write stdout to file - Mekire - Dec-31-2016

Probably something like this?
def F():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
 
 
def subfib(StartNumber, endNumber):
    for cur in F():
        if cur > endNumber:
            return
        if cur >= StartNumber:
            yield cur
 
def lines():
    with open('fibo.txt', 'w') as f:
        for fib in subfib(2, 400):
            f.write("{} ".format(fib))


if __name__ == "__main__":
    lines()
If this isn't what you need then you need to be more explicit about what the final file should look like.


RE: Write stdout to file - Larz60+ - Jan-01-2017

Also see http://python-forum.io/Thread-class-that-Redirects-text-from-stdio-to-file?highlight=Toggle


RE: Write stdout to file - mcmxl22 - Jan-01-2017

Thanks @Mekire! I was able to make it work how I needed it.