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文件。但每次重写文件。
如何防止这种情况发生?
答案 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")