如何在一个文件中腌制多个对象?

问题描述:

就我而言,我希望将两个单独的列表(使用 pickle.dump())腌制到一个文件中,然后从单独的文件中检索它们,但是当使用 pickle.load 时() 我一直在努力寻找一个列表的结束位置和下一个列表的开始位置,因为我根本不知道如何以一种易于检索的方式 pickle.dump() 它们,即使在浏览了文档之后.

In my case, I wish to pickle (using pickle.dump()) two separate lists to a file, then retrieve these from a separate file, however when using pickle.load() I have struggled finding where one list ends and the next begins as I simply don't know how to pickle.dump() them in a manner that makes them easy to retrieve, even after looking through documentation.

pickle 将按照您转储它们的顺序读取它们.

pickle will read them in the same order you dumped them in.

import pickle

test1, test2 = ["One", "Two", "Three"], ["1", "2", "3"]
with open("C:/temp/test.pickle","wb") as f:
    pickle.dump(test1, f)
    pickle.dump(test2, f)
with open("C:/temp/test.pickle", "rb") as f:
    testout1 = pickle.load(f)
    testout2 = pickle.load(f)

print testout1, testout2

打印出['One', 'Two', 'Three'] ['1', '2', '3'].要pickle任意数量的对象,或者只是让它们更容易使用,您可以将它们放在一个元组中,然后只需pickle一个对象.

Prints out ['One', 'Two', 'Three'] ['1', '2', '3']. To pickle an arbitrary number of objects, or to just make them easier to work with, you can put them in a tuple, and then you only have to pickle the one object.

import pickle

test1, test2 = ["One", "Two", "Three"], ["1", "2", "3"]
saveObject = (test1, test2)
with open("C:/temp/test.pickle","wb") as f:
    pickle.dump(saveObject, f)
with open("C:/temp/test.pickle", "rb") as f:
    testout = pickle.load(f)

print testout[0], testout[1]

打印出['One', 'Two', 'Three'] ['1', '2', '3']