[英]Saving output of a loop to file
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. 我想将for循环的输出(0,1,1,2,3)保存到文件中,但我的代码只写了循环的最后一个值(3)。 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()
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()
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')
Well its not only easy but far more easy then easy ... :P 那么它不仅容易,而且容易得多......: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. 这将以附加模式打开您的文件。
Give a try to yield
instead of return
试着yield
而不是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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.