如何追加到文件而不是覆盖它?
当前回答
当我们使用这行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")
其他回答
在文件末尾附加更多文本的最简单方法是使用:
with open('/path/to/file', 'a+') as file:
file.write("Additions to file")
file.close()
open(…)语句中的a+指示以追加模式打开文件,并允许读取和写入访问。
使用完file.close()关闭打开的所有文件也是一个很好的做法。
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
如果多个进程正在写入文件,则必须使用追加模式,否则数据将被打乱。追加模式将使操作系统将每次写入都放在文件末尾,而不管写入者认为自己在文件中的位置。这是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");
追加最多并不意味着“打开文件,打开文件后转到文件末尾一次”。这意味着,“打开文件,我所做的每一次写入都将在文件末尾”。
警告:要使其生效,您必须在一次写入调用中一次性写入所有记录。如果您在多个写操作之间分割数据,其他写操作人员可以也将在您的写操作之间进行写操作,从而损坏您的数据。
您可能希望传递“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")
文档列出了所有可用模式。
推荐文章
- 把if-elif-else语句放在一行中?
- 我如何结合两个数据框架?
- 如何计数列表中唯一值的出现
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?