如何追加到文件而不是覆盖它?
当前回答
如果要附加到文件
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”)时,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()关闭打开的所有文件也是一个很好的做法。
我总是这样做,
f = open('filename.txt', 'a')
f.write("stuff")
f.close()
它很简单,但非常有用。
你也可以用打印代替书写:
with open('test.txt', 'a') as f:
print('appended text', file=f)
如果test.txt不存在,将创建它。。。
您可能希望传递“a”作为模式参数。请参阅open()的文档。
with open("foo", "a") as f:
f.write("cool beans...")
对于更新(+)、截断(w)和二进制(b)模式,模式参数还有其他排列,但最好以“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中获得所有直接子目录