如何追加到文件而不是覆盖它?
当前回答
您需要以追加模式打开文件,将“a”或“ab”设置为模式。请参见open()。
当您以“a”模式打开时,写入位置将始终位于文件末尾(追加)。您可以用“a+”打开以允许读取、向后搜索和读取(但所有写入仍将位于文件末尾!)。
例子:
>>> with open('test1','wb') as f:
f.write('test')
>>> with open('test1','ab') as f:
f.write('koko')
>>> with open('test1','rb') as f:
f.read()
'testkoko'
注意:使用“a”与使用“w”打开并查找文件结尾不同-请考虑如果另一个程序打开文件并在查找和写入之间开始写入,可能会发生什么情况。在某些操作系统上,使用“a”打开文件可以保证后续的所有写入都会自动附加到文件末尾(即使文件因其他写入而增长)。
关于“A”模式如何运行的更多细节(仅在Linux上测试)。即使向后搜索,每次写入都会附加到文件末尾:
>>> f = open('test','a+') # Not using 'with' just to simplify the example REPL session
>>> f.write('hi')
>>> f.seek(0)
>>> f.read()
'hi'
>>> f.seek(0)
>>> f.write('bye') # Will still append despite the seek(0)!
>>> f.seek(0)
>>> f.read()
'hibye'
事实上,fopen手册页指出:
以追加模式打开文件(a作为模式的第一个字符)导致此流的所有后续写入操作发生在文件结尾,就像在调用之前一样:fseek(流,0,SEEK_END);
旧的简化答案(不与一起使用):
示例:(在实际程序中,使用关闭文件-请参阅文档)
>>> open("test","wb").write("test")
>>> open("test","a+b").write("koko")
>>> open("test","rb").read()
'testkoko'
其他回答
“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("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)
您可能希望传递“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")
有时,初学者会遇到这个问题,因为他们试图在循环中打开和写入文件:
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))