python - Saving scores with Pickle -
i'm quite new python. have written program saves high scores in pickle dictionary object , calls it. have few questions program maybe can me with.
- how store , update data through multiple app launches? (quitting python idle , reopening not save these scores)
- solved: why program write new score of same person no matter if higher or lower?
-
import pickle high_scores = {"adam smith": 65536, "john doe": 10000} open("highscores.pkl","wb") out: pickle.dump(high_scores, out) new_score = (raw_input("enter name ").title(), int(raw_input("enter score "))) open("highscores.pkl","rb") in_: high_scores = pickle.load(in_) if new_score[0] not in high_scores: high_scores[new_score[0]] = new_score[1] if new_score[0] in high_scores , new_score[1] not in high_scores.values(): high_scores[new_score[0]] = new_score[1] else: pass open("highscores.pkl","wb") out: pickle.dump(high_scores, out) print("-" * 80) name, score in high_scores.items(): print("{{name:>{col_width}}} | {{score:<{col_width}}}".format(col_width=(80-3)//2).format(name=name, score=score))
as per padraic's suggestion, code below checks see if highscores.pkl
exists. if does, unpickles contents high_scores
, otherwise 2 default scores assigned it.
from there, after new score has been entered, check see if key (player name) exists in high_scores
. if does, , new score higher old score replaced. if key not exist, add player , score.
after check has been carried out, high_scores
saved writing highscores.pkl
file.
import pickle import os high_scores = {} if os.path.isfile('highscores.pkl'): open("highscores.pkl", "rb") f: high_scores = pickle.load(f) else: high_scores = {"adam smith": 65536, "john doe": 10000} new_score = (raw_input("enter name ").title(), int(raw_input("enter score "))) if new_score[0] in high_scores: if new_score[1] > high_scores[new_score[0]]: high_scores[new_score[0]] = new_score[1] else: high_scores[new_score[0]] = new_score[1] open("highscores.pkl","wb") out: pickle.dump(high_scores, out) print("-" * 80) name, score in high_scores.items(): print("{{name:>{col_width}}} | {{score:<{col_width}}}".format(col_width=(80-3)//2).format(name=name, score=score))
Comments
Post a Comment