pythoner pythoner - 1 year ago 83
Python Question

How to keep list changes when program ends?

I have made simple Submit score option. User inputs name and score, and they are save to the list. List saves only top 10 scores. Than, list is printed to .txt file. But it works only while program is working. When i start it again, there's only default score in .txt file. User scores weren't saved. I'm using pickle module for that.

This is piece of my code. It's Python 3.4 and Tkinter.
Keep on mind that I'm learning python.

# This is inside class
# ...
# ...

self.printto = tk.Button(self, text="Submit",

self.high_scores = [
('Liz', 1800)

def highscore(self):
name = self.name_ent.get()
score = int(self.score_ent.get())

self.high_scores.append((name, score))
high_scores = sorted(self.high_scores, key=itemgetter(1), reverse=True)[:10]

with open('D:\Desktop/mytext.txt', 'wb') as f:
pickle.dump(high_scores, f)

Answer Source

You are only saving data to file, but you are not reading it. You must open the file at the beginning of the program and read scores from it.

with open('D:\Desktop/mytext.txt', 'rb') as f:
    high_scores = pickle.load(f)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download