我使用 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]]
最佳答案
当 try:
block 成功更新文件时,您是否也忘记了 pickle.dump
?这可能就是您想要的:
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/