python将列表保存到文件中

时间:2016-07-10 10:10:25

标签: python list load pickle

使用时

with open('savefile.dat', 'wb') as f:
    pickle.dump([player], f, protocol=2)

保存列表,然后尝试打开它可行,但是当我使用此代码时,它会给我一个错误:

open("KappaClickerSave.json", "rb")
with open("KappaClickerSave.json", "rb") as f:

    savefile = pickle.load(f)
    house1 = savefile [0]
    house2 = savefile [1]
    house3 = savefile [2]
    house4=savefile [3]

house2 = savefile [1] IndexError: list index out of range我在列表中有10件事。请注意,列表中的10个项目都使用append

放入列表中

编辑:这也是关于我的保存功能的保存部分:

open('KappaClickerSave.json', 'wb')
with open('KappaClickerSave.json', 'wb') as f:
    pickle.dump([savefile], f, protocol=2)

所有追加都在那之前的行

编辑2:这是关于保存的所有代码:

import json
import pickle

15行后......

(这会加载所有房屋)

open("KappaClickerSave.json", "rb")
with open("KappaClickerSave.json", "rb") as f:
    savefile = pickle.load(f)
    house = savefile [0]
    house2 = savefile [1]
    house3 = savefile [2]
    house4=savefile [3]
    house5=savefile [4]
    house6=savefile [5]
    house7=savefile [6]
    house8=savefile[7]
    house9=savefile[8]
    house10=savefile[9]
    house11=savefile [10]
    house12= savefile [11]
    house13= savefile [12]
    house14= savefile [13]

50行以后......

(这会将所有门牌号码添加到列表中)

def save():

    savefile = []
    savefile.append(house1)
    savefile.append(house2)
    savefile.append(house3)
    savefile.append(house4)
    savefile.append(house5)
    savefile.append(house6)
    savefile.append(house7)
    savefile.append(house8)
    savefile.append(house9)
    savefile.append(house10)
    savefile.append(house11)
    savefile.append(house12)
    savefile.append(house13)
    savefile.append(house14)
    open('KappaClickerSave.json', 'wb')
    with open('KappaClickerSave.json', 'wb') as f:
        pickle.dump(savefile, f, protocol=2)

编辑3:以防万一重要,这里是我的保存文件中写的代码:

€] q] q(G G @ G G @ G G @ G G?ðG@ o G G G @@ GA。“€G ea。

1 个答案:

答案 0 :(得分:0)

您正在使用一个元素保存列表:

with open('savefile.dat', 'wb') as f:
    pickle.dump([player], f, protocol=2)

如果 后,您将append元素编入列表,则不会更改会反映在文件中。你应该只挑选最终结果。

因此,请将您的代码更改为:

my_list = [player]
my_list.append(1) 
# do all the appends
# at the end:
with open('savefile.dat', 'wb') as f:
    pickle.dump(my_list, f, protocol=2)