目录
1.问题背景
通常我们向txt文件写入东西时使用如下代码:
with open("test.txt", "w") as file:
for i in range(10):
file.write(str(i) + "\n")
打开test.txt文件可以看到成功写入:
上述方法可以成功向空白的txt文件写入内容,但是如果向已有内容的txt文件写入信息:
with open("test.txt", "w") as file:
for i in range(90, 100):
file.write(str(i) + "\n")
就会覆盖原有的内容:
而我们想要达到的是如下效果:
2.解决方法
那怎么办呢?解决方法如下:
with open("test.txt", "a") as file:
for i in range(90, 100):
file.write(str(i) + "\n")
只需要将“w”改为“a”即可,哈哈哈哈~~~