我想将for循环的输出(0,1,1,2,3)保存到文件中,但我的代码只写入循环的最后一个值(3)。我该如何解决?
#!/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()
答案 0 :(得分:1)
尝试这个。
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()
答案 1 :(得分:1)
您可能希望了解generators和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')
答案 2 :(得分:1)
好吧,它不仅容易,而且容易得多......:P
使用相同的代码只需在打开时更改文件模式即...
file=open("fib.txt","w") #opens your file in write mode
所以......将其改为
file=open("fib.txt","a") #opens your file in append mode
将以追加模式打开您的文件。
答案 3 :(得分:0)
尝试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()