Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you Pickle multiple objects in one file? [duplicate]

Tags:

python

pickle

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.

like image 755
Drake Avatar asked Feb 20 '17 17:02

Drake


1 Answers

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

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]

Prints out ['One', 'Two', 'Three'] ['1', '2', '3']

like image 59
MackM Avatar answered Sep 19 '22 17:09

MackM