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


当前回答

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

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

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

其他回答

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

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

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

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

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

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

“a”参数表示追加模式。如果你不想每次都使用open,你可以很容易地编写一个函数来实现:

def append(txt='\nFunction Successfully Executed', file):
    with open(file, 'a') as f:
        f.write(txt)

如果您想在结尾以外的其他地方写作,可以使用“r+”†:

import os

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

最后,“w+”参数赋予了更多的自由。具体来说,它允许您在文件不存在时创建该文件,以及清空当前存在的文件的内容。


†该功能的积分归@Primusa

Python有三种主要模式的多种变体,这三种模式是:

'w'   write text
'r'   read text
'a'   append text

因此,要附加到文件,很简单:

f = open('filename.txt', 'a') 
f.write('whatever you want to write here (in append mode) here.')

还有一些模式只会使代码行数更少:

'r+'  read + write text
'w+'  read + write text
'a+'  append + read text

最后,有两种二进制格式的读/写模式:

'rb'  read binary
'wb'  write binary
'ab'  append binary
'rb+' read + write binary
'wb+' read + write binary
'ab+' append + read binary

有时,初学者会遇到这个问题,因为他们试图在循环中打开和写入文件:

for item in my_data:
    with open('results.txt', 'w') as f:
        f.write(some_calculation(item))

问题是,每次打开文件进行写入时,它都会被截断(清除)。

我们可以通过以追加模式打开来解决这个问题;但在这种情况下,通常最好通过颠倒逻辑来解决问题。如果文件只打开一次,那么每次都不会被覆盖;并且只要它是打开的,我们就可以继续写它——我们不必在每次写的时候都重新打开它(Python这样做是没有意义的,因为它会增加所需的代码而没有好处)。

因此:

with open('results.txt', 'w') as f:
    for item in my_data:
        f.write(some_calculation(item))