Python Forum

Full Version: Write stdout to file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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()
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.
Thanks @Mekire! I was able to make it work how I needed it.