问题
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:
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]]
回答2:
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....)
There are several ways around this:
- Pack all of the items into a single list or tuple, and pickle that instead of pickling them individually. You can then unpack on the other side.
- Pickle an integer describing the number of items first. That then tells you how many times to call
pickle.load(). - Just keep unpickling until you hit EOF.
回答3:
Have not previously tried to put more than one thing in a pickle file like that before, but good to see it is possible. Look at this answer. If you call it twice without the with it should get everything out:
f = open("TestPickle.pickle", "r")
ListNames = pickle.load(f)
ListNumbers = pickle.load(f)
f.close()
or you can keep the with like this:
with open("TestPickle.pickle", "rb") as f:
ListNames,ListNumbers = pickle.load(f)
Then,
what if I have an unknown number of items in my pickle file with a number of Datatypes
Is it really a smart idea to just pour something into a pickle file so you don't know anymore what is in it?
来源:https://stackoverflow.com/questions/49261006/load-all-pickled-objects