What does serialization mean?
The process of storing variables to disk is called serialization, in English also called: pickling, serialization, marshalling, fastening.
Conversely, the contents of the variable in the disk read into the memory is deserialized, also known as unpickle, the noun is unpickling.
In Python, there are two modules Cpickle and pickle that can be used for serialization. Only, Cpickle is written in C language, relatively fast. And Pickle, is written in the Python language.
During the import process, you often try to import the Cpickle module first, and if not, import the Pickle module.
try: importas pickleexcept ImportError: import pickle
Serialization: Writing a Python object to a file
For example, the following Dictionary object.
>>> d = dict (name= ' Bob ', age=20,score=88)
>>> Pickle.dumps (d)
"(Dp1\ns ' age ' \np2\ni20\nss ' score ' \np3\ni88\nss ' name ' \np4\ns ' Bob ' \np5\ns."
The dumps () method returns a string so that the string can be written to the file.
The dump (Pyobject, FileObject) method directly serializes the object and writes it to the file.
>>> f = open (' Dump.txt ', ' WB ')
>>> Pickle.dump (d, F)
At this point in the current directory there is already a file dump.txt, but you open a look found nothing
Yes, this is because you forgot to close the file, which is the file or open write state, and it is waiting for
Your other write commands until you close it.
>>> F.close ()
At this point, you'll see a string that will be written.
Deserialization
What should be done to read the Dump.txt information into memory?
Method One: Read the file into memory, become a String object, use Pickle.loads (ASTR) for the string object
>>> f = open ("Dump.txt", ' RB ')
>>> xx = F.read ()
>>> dd = pickle.loads (XX)
>>> DD
{' Age ': ' Score ': ' The ' name ': ' Bob '}
>>>f.closed ()
Method Two: Use Pickle.load (file) to directly act on the file object, and then do not forget to close the file.
>>> f = open ("Dump.txt", ' RB ')
>>> di = Pickle.load (f)
>>> di
{' Age ': ' Score ': ' The ' name ': ' Bob '}
>>> F.close ()
Note: Deserialization produces objects that have the same content as the source object, but they are not an object. Pickle can only be used with Python, and may be incompatible with different versions of Python, so you can only use pickle to save unimportant data.
[Note]python pickle module