如何追加到文件而不是覆盖它?
当前回答
您也可以在r+模式下打开文件,然后将文件位置设置为文件末尾。
import os
with open('text.txt', 'r+') as f:
f.seek(0, os.SEEK_END)
f.write("text to add")
以r+模式打开文件将允许您写入除结尾之外的其他文件位置,而a和a+强制写入结尾。
其他回答
您可能希望传递“a”作为模式参数。请参阅open()的文档。
with open("foo", "a") as f:
f.write("cool beans...")
对于更新(+)、截断(w)和二进制(b)模式,模式参数还有其他排列,但最好以“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
如果要附加到文件
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)
将open()中的模式设置为“a”(追加)而不是“w”(写入):
with open("test.txt", "a") as myfile:
myfile.write("appended text")
文档列出了所有可用模式。
您也可以在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中获得所有直接子目录