我目前有一个高分列表的代码:
scores = []
choice = None
while choice != "0":
print(
"""
High Scores
0 - Quit
1 - List Scores
2 - Add a Score
"""
)
choice = input("Choice: ")
print()
if choice == "0":
print("Goodbye")
elif choice == "1":
print("High Scores\n")
print("NAME\tSCORE")
for entry in scores:
score, name = entry
print(name, "\t", score)
elif choice == "2":
name = input("What is your name? ")
score = int(input("What score did you get? "))
entry = [score, name]
scores.append(entry)
scores.sort(reverse=True)
scores = scores[:10]
else:
print("Sorry, but", choice, "isn't a valid choice.")
任何人都可以告诉我如何添加代码,以便在下次使用该程序时保存高分
答案 0 :(得分:1)
最好的选择是json
module:
import json
def load_scores():
with open("scores.json") as infile:
return json.load(infile)
def save_scores(scores):
with open("scores.json", "w") as outfile:
json.dump(scores, outfile)
现在您可以调用save_scores(scores)
来保存当前的高分榜,然后scores = load_scores()
将其从文件中恢复。