I have a python
class that contains many objects -- some are data structures (lists
, dicts
etc) and some are handlers to other classes (that also contain other data structures...).
Rather than using pickle
to save the entire class & its contents, I was wondering if there is a way to serialize
the data of several desired objects and save them (ONLY them) in a bi开发者_如何学Cnary file?
For example, suppose that I have the following 2 python objects:
myList = [1, 2, 3, 4, 5]
myDict = {'a' : 14, 'b' : 5, 'c' : 65}
What is the best way to save the contents of BOTH of these python
objects in a binary file? ideally, I'd like to save both objects in the same binary file, and be able to load the data later on.
Then create a container class for them (or named tuple, or just a tuple, whatever) and pickle it (or modify the original class so that only those parts that you want are pickled). pickle
is serialisation, and it is the standard Python mechanism to do it. So unless you need e.g. more interoperability between different languages, stick to it.
import pickle
imelda = ('More Mayhem',
'Imelda May',
'2011',
((1, 'Pulling the Rug')
(2, 'Psycho'),
(3, 'Mayhem'),
(4, 'Kentish Town Waltz')))
with open("imelda.pickle", "wb") as pickle_file:
pickle.dumps(imelda, pickle_file)
精彩评论