1. Pickle package
(1) Convert objects in memory into text streams:
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
Use the pickle.dumps() method to convert the object summer into a string picklesring (that is, a text stream). Then we can use the ordinary text storage method to store the string in the file (text file input and output).
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
The object summer is stored in the file a.pkl
(2), reconstruct the object
First, we To read text from text, store to string (text file input and output). Then use the pickle.loads(str) method to convert the string into an object. Remember, our program must already have a class definition for the object at this time.
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 identical to the pickle package (there are differences) Rarely used in fact), the difference is that cPickle is written in c language and is 1000 times faster than the pickle package. For the above example, if we want to use the cPickle package, we can change the import statement to:
import cPickle as pickle
There is no need to make any changes.