1

I want to save the output (0,1,1,2,3) of for-loop to the file but my code writes just the last value (3) of loop. How can I fix it?

#!/usr/bin/python

def fib(n):
    a, b = 0, 1
    for i in range(0, n):
        a, b = b, a + b
    return a
for c in range(0, 5):
   print(fib(c))
   file=open("fib.txt","w")
   s = str(fib(c))
   file.write(s+"\n")
#   file.write("%s\n" % fib(c))
   file.close()
erhan
  • 317
  • 1
  • 6
  • 16

4 Answers4

1

Try to this.

def fib(n):
    a, b = 0, 1
    for i in range(0, n):
        a, b = b, a + b
    return a
file=open("fib.txt", "a")
for c in range(0, 5):
   print(fib(c))
   s = str(fib(c))
   file.write(s + "\n")
file.close()
ZdaR
  • 22,343
  • 7
  • 66
  • 87
Haresh Shyara
  • 1,826
  • 10
  • 13
1

You might want to read about generators and context managers:

def fib(n):
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
        yield a

with open("fib.txt","w") as f:
    for x in fib(5):
        f.write(str(x) + '\n')
Vincent
  • 12,919
  • 1
  • 42
  • 64
1

Well its not only easy but far more easy then easy ... :P

use the same code just change the mode of file while opening that is...

file=open("fib.txt","w") #opens your file in write mode

so.. change it to

file=open("fib.txt","a") #opens your file in append mode

which will open your file in append mode.

kedarkhetia
  • 101
  • 9
0

Give a try to yield instead of return

#!/usr/bin/python

def fib(n):
    a, b = 0, 1
    for i in range(0, n):
        a, b = b, a + b
        yield a
for c in range(0, 5):
   print(fib(c))
   file=open("fib.txt","w")
   for s in str(fib(c)):
       file.write(s+"\n")
   file.close()
farhawa
  • 10,120
  • 16
  • 49
  • 91