如何追加到文件而不是覆盖它?
当前回答
我总是这样做,
f = open('filename.txt', 'a')
f.write("stuff")
f.close()
它很简单,但非常有用。
其他回答
如果多个进程正在写入文件,则必须使用追加模式,否则数据将被打乱。追加模式将使操作系统将每次写入都放在文件末尾,而不管写入者认为自己在文件中的位置。这是nginx或apache等多进程服务的常见问题,因为同一进程的多个实例正在写入同一日志文件考虑一下如果你试图寻找会发生什么,然后写下:
Example does not work well with multiple processes:
f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");
writer1: seek to end of file. position 1000 (for example)
writer2: seek to end of file. position 1000
writer2: write data at position 1000 end of file is now 1000 + length of data.
writer1: write data at position 1000 writer1's data overwrites writer2's data.
通过使用追加模式,操作系统将在文件末尾放置任何写入。
f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");
追加最多并不意味着“打开文件,打开文件后转到文件末尾一次”。这意味着,“打开文件,我所做的每一次写入都将在文件末尾”。
警告:要使其生效,您必须在一次写入调用中一次性写入所有记录。如果您在多个写操作之间分割数据,其他写操作人员可以也将在您的写操作之间进行写操作,从而损坏您的数据。
您也可以在r+模式下打开文件,然后将文件位置设置为文件末尾。
import os
with open('text.txt', 'r+') as f:
f.seek(0, os.SEEK_END)
f.write("text to add")
以r+模式打开文件将允许您写入除结尾之外的其他文件位置,而a和a+强制写入结尾。
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
我总是这样做,
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()关闭打开的所有文件也是一个很好的做法。