-1

I have this example array

endings = ["Example1","Example2"]

This is my save code

reader = open("e_save.txt","r")
  append = open("e_save.txt","a")
  for i in endings:
    print(i)
    if i not in reader.read():
      append.write(os.linesep)
      append.write(i)
  print(reader)

If I run it multiple times I get outcomes like this: Example1 Example2 Example2 Example2 It just adds more and more however the first one works perfectly. Anyone knows a fix?

2 Answers2

2

The problem is with the file mode of open("e_save.txt","a"). Try using open("e_save.txt","w").

See: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files for more details. Modes description: https://docs.python.org/3/library/functions.html#open

'r' open for reading (default)

'w' open for writing, truncating the file first

'x' open for exclusive creation, failing if the file already exists

'a' open for writing, appending to the end of file if it exists

'b' binary mode

't' text mode (default)

'+' open for updating (reading and writing)
Lukasz Wiecek
  • 414
  • 2
  • 8
0

Opening the file with the option a means anything you write gets added to the end of the file, try it like this

open("e_save.txt","w")

IF you do want to append to the file, try checking with the last line, you can refer here to get the last line

edit: you don't need the reader, you can read with append

Bora Varol
  • 192
  • 1
  • 11