1. pickle package (1). convert the objects in the memory into text streams: importpickle # defineclassclassBird (object): have_featherTrueway_of_reproductioneggsummerBird (... 1. pickle package
(1) convert an object in memory into a text stream:
import pickle # define class class Bird(object): have_feather = True way_of_reproduction = 'egg' summer = Bird() # construct an object picklestring = pickle.dumps(summer) # serialize object
The pickle. dumps () method can be used to convert the object summer into a string picklestring (text stream ). Then we can store the string in a file (input and output of a text file) by using the storage method of common text ).
Of course, we can also use the pickle. dump () method to combine the above two parts into one:
import pickle # define class class Bird(object): have_feather = True way_of_reproduction = 'egg' summer = Bird() # construct an object fn = 'a.pkl' with open(fn, 'w') as f: # open file with write-mode picklestring = pickle.dump(summer, f) # serialize and save object
Object summer is stored in file a. pkl
(2) rebuilding objects
First, we need to read the text from the text and store it to a string (input and output of a text file ). Then, use the pickle. loads (str) method to convert the string into an object. Remember, at this time, our program must have the class definition of this object.
In addition, we can also use the pickle. load () method to merge the above steps:
import pickle # define the class before unpickle class Bird(object): have_feather = True way_of_reproduction = 'egg' fn = 'a.pkl' with open(fn, 'r') as f: summer = pickle.load(f) # read file and build object
2. cPickle package
The functions and usage of the cPickle package are almost the same as those of the pickle package (the difference is actually seldom used). The difference is that cPickle is written in C language and 1000 times faster than the pickle package. For the above example, if you want to use the cPickle package, we can change the import statement:
Import cPickle as pickle
You do not need to make any changes.