如何追加到文件而不是覆盖它?
当前回答
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
其他回答
当我们使用这行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()关闭打开的所有文件也是一个很好的做法。
如果多个进程正在写入文件,则必须使用追加模式,否则数据将被打乱。追加模式将使操作系统将每次写入都放在文件末尾,而不管写入者认为自己在文件中的位置。这是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");
追加最多并不意味着“打开文件,打开文件后转到文件末尾一次”。这意味着,“打开文件,我所做的每一次写入都将在文件末尾”。
警告:要使其生效,您必须在一次写入调用中一次性写入所有记录。如果您在多个写操作之间分割数据,其他写操作人员可以也将在您的写操作之间进行写操作,从而损坏您的数据。
你也可以用打印代替书写:
with open('test.txt', 'a') as f:
print('appended text', file=f)
如果test.txt不存在,将创建它。。。
您也可以在r+模式下打开文件,然后将文件位置设置为文件末尾。
import os
with open('text.txt', 'r+') as f:
f.seek(0, os.SEEK_END)
f.write("text to add")
以r+模式打开文件将允许您写入除结尾之外的其他文件位置,而a和a+强制写入结尾。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录