0

In one of my games, I need to append to the end of the game saves file if I the user is new or change the balance in the file if the user already has a game save. This requires me to open the file separately in write and append modes. Is there a way I could do this sumultaneously?

def write_to_txt(self):
    if self.saved_game:
        with open("Game Saves.txt", "w") as f:
            new_saved_game = self.list_saved_game[0] + self.list_saved_game[1][:10] + str(self.balance) + "\n"
            f.write(''.join(self.contents_of_txt_file).replace(self.saved_game, new_saved_game))
    else:
        with open("Game Saves.txt", "a") as f:
            f.write("User: {}\nBalance = {}\n".format(self.name, self.balance))
Anonymous Coder
  • 512
  • 1
  • 6
  • 22
  • Mode "append" merely means the file pointer is at the end *by default*. But you can maneuver through a single open file with [`file.seek`](https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects). – Jongware Feb 23 '18 at 21:33
  • `f.seek(0)` and then `f.truncate()` worked but `f.truncate(0)` did not. Why is that? – Anonymous Coder Feb 23 '18 at 21:38
  • Interesting. From the documentation I gather it should do the same ... Ah, [here](https://stackoverflow.com/q/8945370) is a relevant earlier discussion. – Jongware Feb 23 '18 at 21:45

2 Answers2

0

It seems to me that you want a way to delete the contents of the file while in append mode? You could open it in append mode and then use the .truncate() method when you want to start writing from a clean file (as you would if you opened it in write mode).

See this answer: How to erase the file contents of text file in Python?

divibisan
  • 11,659
  • 11
  • 40
  • 58
0

You can use something like:

with open("Game Saves.txt", ('a' if self.saved_game else 'w')) as f:
    <rest of the code>