Python写入文件而不覆盖当前的txt

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22441803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:57:02  来源:igfitidea点击:

Python write to file without overwriting current txt

python

提问by

with open("games.txt", "w") as text_file:
    print(driver.current_url)
    text_file.write(driver.current_url + "\n")

I'm using this code right now, but when it writes to the file it overwrites the old content. How can I simply add to it without erasing the content that's already there.

我现在正在使用此代码,但是当它写入文件时,它会覆盖旧内容。如何在不删除已经存在的内容的情况下简单地添加它。

采纳答案by Paulo Bu

Instead of "w"use "a"(append) mode with openfunction:

而不是"w"使用"a"(附加)模式与open功能:

with open("games.txt", "a") as text_file: