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


当前回答

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

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

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

其他回答

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

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

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

我总是这样做,

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

它很简单,但非常有用。

您也可以在r+模式下打开文件,然后将文件位置设置为文件末尾。

import os

with open('text.txt', 'r+') as f:
    f.seek(0, os.SEEK_END)
    f.write("text to add")

以r+模式打开文件将允许您写入除结尾之外的其他文件位置,而a和a+强制写入结尾。

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

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

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

当我们使用这行open(文件名,“a”)时,a表示附加文件,这意味着允许向现有文件插入额外的数据。

您可以使用以下行将文本附加到文件中

def FileSave(filename,content):
    with open(filename, "a") as myfile:
        myfile.write(content)

FileSave("test.txt","test1 \n")
FileSave("test.txt","test2 \n")