我想將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()
以追加模式打開文件:'file = open(「fib.txt」,「a」) – Igle
[您如何追加到Python中的文件?](http://stackoverflow.com/ question/4706499/how-do-you-append-to-a-file-in-python) – Igle
當你以可寫模式打開文件時,它會改寫內容使用追加模式。 – ZdaR