Someone
Someone

Reputation: 55

Is there a way to append and read a text file in python?

I am trying to make a game in python 3.6 that saves data using a text file.

text = open("text_file.txt", "a")
text.write("Line 1")
text.write("Line 2")
text.write("Line 3")
text.close()
text = open("text_file.txt", "r")
print(text.read())
text.close()

Is there an easier way to do this? I know about 'r+', but it is a combination of read and write. The problem with that is that the write part of it resets the text document back to blank when it opens the file.

Upvotes: 1

Views: 2269

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

From the fopen(3) man page:

   a+     Open  for  reading  and appending (writing at end of file).  The
          file is created if it does not exist.  The initial file position
          for  reading  is  at  the  beginning  of the file, but output is
          always appended to the end of the file.

Upvotes: 3

Related Questions