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()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
  How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file? JohnJSal 12 28,466 Feb-13-2025, 04:48 AM
Last Post: tomhansky
  subprocess_run and stdout flux paul18fr 2 607 Jan-09-2025, 08:50 PM
Last Post: Gribouillis
  How to write variable in a python file then import it in another python file? tatahuft 4 1,016 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  [SOLVED] [Linux] Write file and change owner? Winfried 6 1,688 Oct-17-2024, 01:15 AM
Last Post: Winfried
  Failing to iterate over captured StdOut tester_V 4 1,679 Jul-12-2024, 03:36 PM
Last Post: deanhystad
  What does .flush do? How can I change this to write to the file? Pedroski55 3 1,447 Apr-22-2024, 01:15 PM
Last Post: snippsat
  [subprocess] Why stdout sent to stderr? Winfried 3 2,357 Jan-26-2024, 07:26 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 1,690 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  write to csv file problem jacksfrustration 11 5,554 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 4,028 Nov-09-2023, 10:56 AM
Last Post: mg24

Forum Jump:

User Panel Messages

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