Есть ли способ добавить и прочитать текстовый файл в Python? - PullRequest
0 голосов
/ 13 мая 2018

Я пытаюсь создать игру на Python 3.6, которая сохраняет данные в текстовом файле.

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()

Есть ли более простой способ сделать это? Я знаю о 'r +', но это комбинация чтения и записи. Проблема в том, что при записи файла его часть записи сбрасывает текстовый документ обратно на пустой.

1 Ответ

0 голосов
/ 13 мая 2018

со страницы руководства fopen(3):

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