A binary sequence is stored in the computer's memory.
We can directly fetch the data from the location of an object, convert it to a text stream (the process is called serialize), and then deposit the text stream into a file.
Since Python is referring to the class definition of an object when creating an object, when we read the object from the text, we must have the class definition of the object handy to know how to reconstruct the object.
When reading from a file, for Python's built-in (built-in) objects (such as integers, dictionaries, tables, and so on), it is not necessary for us to define classes in the program because their class definitions are already loaded into memory.
However, for a user-defined object, you must define the class before you can load the object from the file.
A pickle package for the above process, the most common tool is the pickle package in Python.
1 Convert an in-memory object into a text stream:
Import Pickleclass Bird (object): have_feather = True way_of_reproduction = ' egg ' summer = Bird () 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.
Import Pickleclass Bird (object): have_feather = True way_of_reproduction = ' egg ' summer = Bird () FileName = ' Save.pkl ' with open (FileName, ' W ') as f: # Open file with write-mode picklestring = Pickle.dump (Summer, F) # serialize and save Object
Object summer stored in file save.pkl
2 Rebuilding an object first, we are going 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.
Import Pickle # define the class before Unpickleclass Bird (object): have_feather = True way_of_reproduction = ' egg ' fileName = ' save.pkl ' with open (FileName, ' R ') as F: summer = Pickle.load (f) # Read file and build object
The function and usage of the Cpickle bag Cpickle package are almost identical with the pickle package, and the difference is seldom used in the place;
The difference is that Cpickle is based on the C language, which 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.
Python Learning Note 12: Object serialization of the standard library