使用pickle从列表中解压缩变量-Python

时间:2019-03-13 18:36:19

标签: python for-loop serialization save pickle

我正在使用Python 3创建基于文本的RPG,并且正在使用pickle进行序列化/保存。我想做的是,不是将每个变量都输入pickle的dump函数中,而是将它们放在列表中,以便以后保存动态数据,例如,如果玩家在某个图块中将树砍下,世界,它将其添加到玩家下次保存时要保存的事物列表中。转储功能适用于列表和类似这样的for循环

    def save(self):
    save = input("What would you like to name the save?(This will overwrite): ")
    y = 0
    for x in self.gsd:
        pickle.dump([x], open("{0}.tin".format(save), "wb"))

“ self.gsd”是“常规保存数据”的列表。列表如下所示:

self.gsd = [self.scwpriv, self.scwvisited, self.wallet[I.goldpiece], self.skillblacksmith, self.skillgunsmith, self.skillfishing, self.skillleatherwork, self.skillbuilding, self.skillmining, self.skillforaging, self.skillhunting, self.skillcooking, self.skillalch, self.xpblacksmith, self.xpblacksmithnext, self.xpbuilding, self.xpbuildingnext, self.xphunting, self.xphuntingnext, self.xpcooking, self.xpcookingnext, self.xpfishing, self.xpfishingnext, self.xpforaging, self.xpforagingnext,
                 self.xpmining, self.xpminingnext, self.xpalch, self.xpalchnext, self.xpgunsmith, self.xpgunsmithnext, self.xpforaging, self.xpforagingnext, self.xpleatherwork, self.xpleatherworknext, self.stackinv, self.maxhealth, self.inventory, self.questlog, self.compquests, self.name, self.health, self.xpos, self.ypos, self.rs, self.ms, self.hs, self.cs, self.ps, self.fs, self.damage, self.gundamage, self.shot, self.reloading, self.defence, self.status, self.fighting, self.ammo, self.gold, self.devenabled]

当我使用转储通过for循环将列表中的每个变量保存时,它似乎可以工作。问题是当我尝试使用相同的方法将其重新加载到pickle中时,使用另一个for循环,如下所示:

    def loadt(self):
    load = input("What file would you like to load: ")
    for x in self.gsd:
        x = pickle.load(open("{0}.tin".format(load), "rb"))

没有错误,不会崩溃,但是简单明了不会加载变量。我究竟做错了什么?我可以不使用for循环用pickle解压变量吗?

0 个答案:

没有答案