55
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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • The option "a" will allow writing only at the end of the file. Use open("games.txt", "r+") if you want keep the old content but also be allowed to overwrite parts of the initial content with what you want by file seeking. The list of available options might also be useful: https://docs.python.org/3.8/library/functions.html#open – Burcea Bogdan Madalin May 22 '23 at 23:11

1 Answers1

137

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

with open("games.txt", "a") as text_file:
Paulo Bu
  • 29,294
  • 6
  • 74
  • 73