2012-01-15 68 views
3

所以我的代碼看起來是這樣的.... 的,但我想一直將數據添加到文件 結束時,我會怎麼做這將數據添加到結束現有的文件蟒蛇

try: 
    f = open("file.txt", "w") 
    try: 
     f.write('blah') # Write a string to a file 
     f.writelines(lines) # Write a sequence of strings to a file 
    finally: 
     f.close() 
except IOError: 
    pass 

回答

13

打開文件中使用,而不是'w''a'(追加)(寫截斷)

除此之外,你可以做try..finally塊以下isntead:

with open('file.txt', 'a') as f: 
    f.write('blah') 
    f.writelines(lines) 

with塊會自動注意關閉塊末尾的文件。

4

用「a」而不是「w」打開文件

+0

** Re ** open?如果他之前用'w'打開它,它已經是空的了。 – ThiefMaster 2012-01-15 15:29:36