将数据添加到现有文件python的末尾

时间:2012-01-15 15:27:00

标签: python file-io

所以我的代码看起来像这样.... 但我想总是将数据添加到文档的末尾 我该怎么做

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

2 个答案:

答案 0 :(得分:14)

使用'a'(追加)而不是'w'(写入,截断)

打开文件

除此之外,您可以执行以下操作,而不是try..finally块:

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

with块会自动关闭在块结束时关闭文件。

答案 1 :(得分:4)

用“a”而不是“w”打开文件

相关问题