Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load all pickled objects [duplicate]

Tags:

python

pickle

import pickle

ListNames = [["Name1","City1","Email1"],["Name2","City2","Number2"]]
ListNumbers = [1,2,3,4,5,6,7,8]

with open ("TestPickle.pickle","wb") as fileSaver:
    pickle.dump(ListNames,fileSaver)
    pickle.dump(ListNumbers,fileSaver)

with open ("TestPickle.pickle","rb") as fileOpener:
    print(pickle.load(fileOpener))

The output is:

[['Name1', 'City1', 'Email1'], ['Name2', 'City2', 'Number2']]

How do I get pickle to load the ListNumbers too

I know I can just print pickle.load again but what if I have an unknown number of items in my pickle file with a number of Datatypes (e.g: lists, tuples, dictionaries, strings....)

Thanks


1 Answers

I am not sure if this i the correct approach.

import pickle

ListNames = [["Name1","City1","Email1"],["Name2","City2","Number2"]]
ListNumbers = [1,2,3,4,5,6,7,8]

with open ("TestPickle.pickle","wb") as fileSaver:
    pickle.dump(ListNames,fileSaver)
    pickle.dump(ListNumbers,fileSaver)
obj = []
with open("TestPickle.pickle","rb") as fileOpener:
    while True:
        try:
            obj.append(pickle.load(fileOpener))
        except EOFError:
            break
print obj

Output:

[[['Name1', 'City1', 'Email1'], ['Name2', 'City2', 'Number2']], [1, 2, 3, 4, 5, 6, 7, 8]]
like image 167
Rakesh Avatar answered Jun 22 '26 12:06

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!