我在這裏有一些使用「pickle」模塊的python 3代碼。它應該存儲遊戲的高分。當我再次打開程序時,它會給我默認的「A:100 ...」高分。Python酸洗問題
def __init__(self):
self.filename = "highscores.dat"
self.numScores = 5
if not os.path.isfile(self.filename):
self.file = open(self.filename, "wb")
self.scores = [100 for i in range(self.numScores)]
self.names = ["A", "B", "C", "D", "E"]
self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
self.updateFile()
else:
file = open(self.filename, "rb")
self.highscores = pickle.load(file)
file.close()
self.file = open(self.filename, "wb")
self.names = [highscore[0] for highscore in self.highscores]
self.scores = [highscore[1] for highscore in self.highscores]
def addScore(self, name, score):
self.scores.append(score) #Add new score
self.scores.sort(reverse = True) #Sort
self.names.insert(self.scores.index(score), name)
self.names = self.names[:self.numScores] # Top 5
self.scores = self.scores[:self.numScores]
self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
self.updateFile()
def updateFile(self):
pickle.dump(self.highscores, self.file)
這只是代碼中我認爲存在問題的部分。如果需要,我會發布更多信息。我會很樂意回答你的問題。謝謝。
如果您要使用完整的絕對路徑名稱,那麼它是否有效? –
正如「C:\ Users \ Bobby \ Dropbox \ LD25 \ highscores.dat」一樣?我只是測試它,它也有同樣的問題。 – user1149589
您可能希望在'__init__'中插入一個print語句來查看那裏的'.isfile()'測試發生了什麼。該文件是否創建? –