如何追加到文件而不是覆盖它?


当前回答

将open()中的模式设置为“a”(追加)而不是“w”(写入):

with open("test.txt", "a") as myfile:
    myfile.write("appended text")

文档列出了所有可用模式。

其他回答

我总是这样做,

f = open('filename.txt', 'a')
f.write("stuff")
f.close()

它很简单,但非常有用。

在文件末尾附加更多文本的最简单方法是使用:

with open('/path/to/file', 'a+') as file:
    file.write("Additions to file")
file.close()

open(…)语句中的a+指示以追加模式打开文件,并允许读取和写入访问。

使用完file.close()关闭打开的所有文件也是一个很好的做法。

您可能希望传递“a”作为模式参数。请参阅open()的文档。

with open("foo", "a") as f:
    f.write("cool beans...")

对于更新(+)、截断(w)和二进制(b)模式,模式参数还有其他排列,但最好以“a”开头。

你也可以用打印代替书写:

with open('test.txt', 'a') as f:
    print('appended text', file=f)

如果test.txt不存在,将创建它。。。

将open()中的模式设置为“a”(追加)而不是“w”(写入):

with open("test.txt", "a") as myfile:
    myfile.write("appended text")

文档列出了所有可用模式。