程序结束时如何保持列表更改?
How to keep list changes when program ends?
我做了简单的提交分数选项。用户输入姓名和分数,并将它们保存到列表中。列表仅保存前 10 个分数。然后,列表被打印到 .txt 文件。但它仅在程序运行时有效。当我再次启动它时,.txt 文件中只有默认分数。用户分数未保存。为此,我正在使用 pickle 模块。
这是我的一段代码。它是 Python 3.4 和 Tkinter。
请记住,我正在学习 python。
# This is inside class
# ...
# ...
self.printto = tk.Button(self, text="Submit",
command=self.highscore
)
self.printto.pack(side="left")
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)
您只是将数据保存到文件,而不是读取它。您必须在程序开始时打开文件并从中读取乐谱。
with open('D:\Desktop/mytext.txt', 'rb') as f:
high_scores = pickle.load(f)
几件事
第一件事:你的问题就在这里
with open('D:\Desktop/mytext.txt', 'wb') as f:
你打开一个文件,不是在追加模式下,而是在创建模式下,所以每次你想向文件中写入一些东西,你只是覆盖现有的。您可能想先阅读它并与您要写的日期进行比较,以获得前 10 名的分数。
第二件事:
使用 pickle
来保存带有 strings/ints
的列表有点矫枉过正。使用 json.dumps/loads
代替
您正在寻找这样的东西吗?阅读文本文件中的乐谱
user_score = {}
with open('D:\Desktop/mytext.txt') as f:
for line in f:
#add user and score to user_score here
我做了简单的提交分数选项。用户输入姓名和分数,并将它们保存到列表中。列表仅保存前 10 个分数。然后,列表被打印到 .txt 文件。但它仅在程序运行时有效。当我再次启动它时,.txt 文件中只有默认分数。用户分数未保存。为此,我正在使用 pickle 模块。
这是我的一段代码。它是 Python 3.4 和 Tkinter。 请记住,我正在学习 python。
# This is inside class
# ...
# ...
self.printto = tk.Button(self, text="Submit",
command=self.highscore
)
self.printto.pack(side="left")
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)
您只是将数据保存到文件,而不是读取它。您必须在程序开始时打开文件并从中读取乐谱。
with open('D:\Desktop/mytext.txt', 'rb') as f:
high_scores = pickle.load(f)
几件事 第一件事:你的问题就在这里
with open('D:\Desktop/mytext.txt', 'wb') as f:
你打开一个文件,不是在追加模式下,而是在创建模式下,所以每次你想向文件中写入一些东西,你只是覆盖现有的。您可能想先阅读它并与您要写的日期进行比较,以获得前 10 名的分数。
第二件事:
使用 pickle
来保存带有 strings/ints
的列表有点矫枉过正。使用 json.dumps/loads
代替
您正在寻找这样的东西吗?阅读文本文件中的乐谱
user_score = {}
with open('D:\Desktop/mytext.txt') as f:
for line in f:
#add user and score to user_score here