pickle - Python for the absolute beginner, Chapter 7 challenge 2 -
i've been going through exercises in book , i've hit bit of road block. challenge to:
"improve trivia challenge game maintains high-scores list in file. program should record player's name , score. store high scores using pickled object."
i've managed save scores list , append list dat file. however, when try view scores/read file seems show first score entered. took @ bat file , seems dumping list correctly, i'm wondering if i'm messing retrieval part?
thanks reading
here's code (before):
def high_score(): """records player's score""" high_scores = [] #add score name = input("what name? ") player_score = int(input("what score? ")) entry = (name, player_score) high_scores.append(entry) high_scores.sort(reverse=true) high_scores = high_scores[:5] # keep top 5 # open new file store pickled list f = open("pickles1.dat", "ab") pickle.dump(high_scores, f) f.close() choice = none while choice !="0": print( """ 0 - quit 1 - show high scores """ ) choice = input("choice: ") print() # exit if choice == "0": print("goodbye") # show score if choice == "1": f = open("pickles1.dat", "rb") show_scores = pickle.load(f) print(show_scores) f.close() input("\n\npress enter exit.")
solution(after):
def high_score(): """records player's score""" # no previous high score file try: open("pickles1.dat", "rb") f: high_scores = pickle.load(f) except eoferror: high_scores = [] #add score // current stuff adding new score... name = input("what name? ") player_score = int(input("what score? ")) entry = (name, player_score) high_scores.append(entry) high_scores.sort(reverse=true) high_scores = high_scores[:5] # keep top 5 # dump scores open("pickles1.dat", "wb") f: pickle.dump(high_scores, f)
there few problems code. @tokenmacguy has identified one, you're appending results onto end of output file, rather overwriting previous values.
there more fundamental issue though. when run highscores
function, starting empty high score list. add single score it, , write out. structure, never have more 1 score being written @ time (and if read you've written properly, 1-element list).
what need add code load high score list file @ start of function, before add new value. need put in special case when there no previous high score file, that's not dificult try
/except
block. here's abbreviated code:
def high_score(): try: open("pickles1.dat", "rb") f: high_scores = pickle.load(f) except filenotfounderror: high_scores = [] # current stuff adding new score, sorting , slicing open("pickles1.dat", "wb") f: # "wb" mode overwrites previous file pickle.dump(high_scores, f) # other stuff, displaying high_scores
a benefit approach don't need reread file later if user asks it, since high_scores
list date already.
Comments
Post a Comment