1. Pickle Bag
(1), converting an in-memory object 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
You can use the Pickle.dumps () method to convert an object summer to a string picklestring (that is, a text stream). We can then store the string in the file (the input and output of the text file) using the normal text storage method.
Of course, we can also use the Pickle.dump () method to combine the above two parts:
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 stored in file a.pkl
(2), rebuilding objects
First, we want to read the text from the text and store it in a string (the input and output of the text file). The string is then converted to an object using the Pickle.loads (str) method. Remember, at this point in our program we must already have the class definition for that object.
In addition, we can 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 an D Build Object
2. Cpickle Bag
The functionality and usage of the Cpickle package is almost identical to the pickle package (where the difference is actually rarely used), except that the Cpickle is written in C and is 1000 times times faster than the pickle package. For the above example, if you want to use the Cpickle package, we can change the import statement to:
Import Cpickle as Pickle
There is no need to make any more changes.