Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write stdout to file
#1
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()
Reply
#2
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.
Reply
#3
Also see http://python-forum.io/Thread-class-that...ght=Toggle
Reply
#4
Thanks @Mekire! I was able to make it work how I needed it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What does .flush do? How can I change this to write to the file? Pedroski55 3 220 Apr-22-2024, 01:15 PM
Last Post: snippsat
  [subprocess] Why stdout sent to stderr? Winfried 3 482 Jan-26-2024, 07:26 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 439 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  write to csv file problem jacksfrustration 11 1,548 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,469 Nov-09-2023, 10:56 AM
Last Post: mg24
  How do I read and write a binary file in Python? blackears 6 6,688 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,113 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Read text file, modify it then write back Pavel_47 5 1,624 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  how to read txt file, and write into excel with multiply sheet jacklee26 14 10,047 Jan-21-2023, 06:57 AM
Last Post: jacklee26
  Performance options for sys.stdout.writelines dgrunwal 11 3,143 Aug-23-2022, 10:32 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020