我已经使用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]]

最佳答案

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)

关于python - 为什么我的二维列表最多包含2个项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42359088/

10-12 18:26