2012-01-15 67 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