为什么我的2-d列表最多包含2个项目

时间:2017-02-21 05:02:16

标签: python python-3.x multidimensional-array pygame pickle

我使用python和pygame做了一个游戏,我刚刚尝试用节省时间和名字来做事。但是当列表中有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]]

1 个答案:

答案 0 :(得分: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)