2017-02-21 65 views
1

我用python和pygame製作了一款遊戲,而我剛剛嘗試着通過節省時間和名字來做些事情。但是,當列表中有2個項目時,第一個項目保存並且正常工作,但每次完成遊戲時秒數項目都會被覆蓋。爲什麼我的2D列表最多容納2個條目

try: 
    openFile = open("times.txt", "rb") 
    runTimes = pickle.load(openFile) 
    runTimes.append([g.name, g.count]) 
    openFile.close() 
except FileNotFoundError: 
    runTimes = [] 
    runTimes.append([g.name, g.count]) 
    openFile = open("times.txt", "wb") 
    pickle.dump(runTimes, openFile) 
    openFile.close() 

if len(runTimes) > 1: 
    print(runTimes) 

運行1 =什麼也沒有發生

運行2

[['Undefined', 7.5], ['Undefined', 8.3]] 

運行3

[['Undefined', 7.5], ['Undefined', 7.5]] 
+0

什麼是'g'?它在哪裏初始化? –

回答

1

你沒忘了pickle.dump也當try:塊成功更新您的文件?這可能是你想要的:

try: 
    openFile = open("times.txt", "rb") 
    runTimes = pickle.load(openFile) 
    openFile.close() 
except FileNotFoundError: 
    runTimes = [] 

runTimes.append([g.name, g.count]) 
openFile = open("times.txt", "wb") 
pickle.dump(runTimes, openFile) 
openFile.close() 

if len(runTimes) > 1: 
    print(runTimes) 
相關問題