琐事游戏 - 我试图写入高分.txt文件

时间:2014-09-21 07:13:47

标签: python python-3.4 file-access

text_file = open("high_score.txt", "w")
text_file.writelines([player_name, "'s score is: ", scores])
text_file.close()
text_file = open("high_score.txt", "r")
print(text_file.read())
text_file.close()

我正在尝试将高分写入.txt文件。但每次重写文件。

如何防止这种情况发生?

2 个答案:

答案 0 :(得分:1)

text_file = open("high_score.txt", "w")更改为text_file = open("high_score.txt", "a")

您以书写模式打开了一个文件(' w'),这会导致删除以前的数据并写入新数据。如果要在不删除以前数据的情况下编写新数据,则应以附加模式打开文件(' a')

答案 1 :(得分:1)

我认为“a”作为第一行中的第二个参数应该可以完成这项工作:

text_file = open("high_score.txt", "a")

来源:http://www.tutorialspoint.com/python/python_files_io.htm