1

I have gone through this website and many others but no one seems to give me the simplest possible answer. In the scrip bellow there are 2 different variables that need to be placed into a single pickle (aka 'test1' and 'test2'); but I am wholly unable to get even the simpler one of the two to load. There are no error messages or anything, and it does appear that something is being written to the pickle but then I close the 'program', re open it, try to load the pickle but the value of 'test1' does not change.

The second question is how to save both to the same pickle? at first i tried using the allStuff variable to store both test1 and test2 then dumping allStuff...the dump seems to be a success but loading does jack. Ive tried a variation where you list each file that should be loaded but this just caused a whole lot of errors and caused me to assault my poor old keyboard...

Please Help.

import pickle

class testing():

    test1 = 1000
    test2 = {'Dogs' : 0, 'Cats' : 0, 'Birds' : 0, 'Mive' : 0}


    def saveload():
            check = int(input(' 1. Save  :  2. Load  : 3. Print  : 4. Add'))
            allStuff = testing.test1, testing.test2
            saveFile = 'TestingSaveLoad.data'

            if check == 1:
                f = open(saveFile, 'wb')
                pickle.dump(testing.test1, f)
                f.close()
                print()
                print('Saved.')
                testing.saveload()


            elif check == 2:
                f = open(saveFile, 'rb')
                pickle.load(f)
                print()
                print('Loaded.')
                testing.saveload()        


            elif check == 3:
                print(allStuff)
                testing.saveload()

            else:
                testing.test1 += 234
                testing.saveload()


testing.saveload()
4

3 回答 3

1

pickle.load文档指出:

从打开的文件对象文件中读取腌制对象表示并返回其中指定的重构对象层次结构。

所以你需要这样的东西:

testing.test1 = pickle.load(f)

但是,要保存和加载多个对象,您可以使用

# to save
pickle.dump(allStuff, f)

# to load
allStuff = pickle.load(f)
testing.test1, testing.test2 = allStuff
于 2013-09-03T15:51:51.623 回答
1

将它们作为元组转储,并在加载时将结果解压缩回两个变量中。

pickle.dump((testing.test1,testing.test2), f)

testing.test1, testing.test2 = pickle.load(f)

然后更改打印以打印这两个项目并忘记,因为每次加载/重新分配时allStuff都必须不断更新(取决于您存储的项目类型)。allStuff

print(testing.test1, testing.test2)

我还将删除递归调用saveLoad()并将任何应该在while循环中重复的内容包装起来,并带有退出选项

if check == 0:
    break
于 2013-09-03T15:53:27.247 回答
1

您目前没有保存重组后的腌制对象。文档说明pickle.load()返回重构的对象。

你应该有类似的东西:

f = open(saveFile, 'rb')
testing.test1 = pickle.load(f)

要保存多个对象,请使用此答案中推荐的方法:

如果您需要保存多个对象,您可以简单地将它们放在一个列表或元组中

另外,我建议使用with关键字打开文件。即使出现问题,这也将确保文件关闭。最终输出示例:

with open(saveFile, 'wb') as f:
    pickle.dump((testing1, testing2), f)

...

with open(saveFile, 'rb') as f:
    testing1, testing2 = pickle.load(f) # Implicit unpacking of the tuple

您可能还需要一个while循环而不是多次调用saveload()- 它会更干净一些。请注意,现在除了退出程序之外,您无法摆脱循环。

于 2013-09-03T15:53:43.430 回答