【发布时间】:2014-03-04 13:17:49
【问题描述】:
我对 Python 非常陌生,我想要实现的是腌制字典,然后使用某种形式的循环(如果我的术语不正确,请道歉!)打印文件中的所有分数。
我正在使用 Python 3.3.3,这是我的尝试,用户输入一个名称和一个分数,它首先保存到一个文件中,然后我尝试打印它。但是我无法打印分数。
import pickle
# store the scores in a pickled file
def save_scores(player, score):
f = open("high_score.dat", "ab")
d = {player:score}
pickle.dump(d, f)
f.close
# print all the scores from the file
def print_scores():
# this is the part that I can't get to work!
with open("high_score.dat", "r") as f:
try:
for player, score in pickle.load(f):
print("Player: ", player, " scored : ", score)
except EOFError:
pass
f.close
def main():
player_name = input("Enter a name: ")
player_score = input("Enter a score: ")
save_scores(player = player_name, score = player_score)
print_scores()
main()
input("\nPress the Enter key to exit")
我在 Google 上搜索过类似问题的 Stackoverflow,但我必须使用错误的术语,因为我还没有找到解决方案。
提前致谢。
【问题讨论】:
标签: python dictionary python-3.3 pickle