2015-05-21 35 views
1

我想將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

以追加模式打開文件:'file = open(「fib.txt」,「a」) – Igle

+1

[您如何追加到Python中的文件?](http://stackoverflow.com/ question/4706499/how-do-you-append-to-a-file-in-python) – Igle

+0

當你以可寫模式打開文件時,它會改寫內容使用追加模式。 – ZdaR

回答

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

你可能想了解generatorscontext 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') 
+0

看起來像你擊敗了我! – pzp

1

那麼其不僅容易的,但更容易那麼容易...:P

使用相同代碼只需更改文件的模式,同時打開即...

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

所以..它更改爲

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

將在追加方式打開文件。