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


当前回答

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

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")

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

如果要附加到文件

with open("test.txt", "a") as myfile:
    myfile.write("append me")

我们声明了变量myfile以打开名为test.txt的文件。open有两个参数,一个是要打开的文件,另一个是表示要对该文件执行的权限或操作类型的字符串

以下是文件模式选项

Mode    Description

'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing. 
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode. 
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)

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

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

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

“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

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

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

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

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