file = open(r"E:/report/report.txt", mode="a+")
file.writelines("PASS\n")
file.close()
with open(r"E:\report/report.txt", mode="r+") as file:
old = file.read() # 先读取内容保存一份
file.seek(0) # 将光标定位到起始位置
file.writelines("Fail\n") # 写入新的数据,现在写入时,会清除覆盖掉原有数据
file.write(old) # 写入之前数据,这次在写入数据时,不会再清除原有数据,而是在尾部添加
运行结果:
D:\Python3.8.6\python.exe D:/PythonWorkSpace/chenbang/test_9.py
Process finished with exit code 0
运行截图:
注意事项:
1、下面使用with方法打开文件的模式是mode=“r+”,如果没有该文件,是不会新建文件的。所以前面需要先用mode=“a+”,如果文件存在就会追加数据,如果文件不存在,就会新建一个。
2、使用open()方法打开文件时要及时关闭。使用with方法打开文件不需要手动关闭。