@Python Pickle Module Learning
The pickle provides a simple persistence feature. You can store the object as a file on disk.
------------------------------------------
Pickle.dump (obj, file[, Protocol])
Serializes the object and writes the resulting data stream to the file object. The parameter protocol is a serialization mode with a default value of 0, which indicates serialization as text. The value of the protocol can also be 1 or 2, which is serialized as a binary representation.
------------------------------------------
Pickle.load (file)
Deserializes the object. Resolves the data in a file to a Python object.
It is important to note that in the case of load (file), Python is able to find the definition of the class, otherwise it will give an error:
such as the following example
[Python]View Plaincopy
- Import Pickle
- Class Person:
- def __init__ (self,n,a):
- self.name=n
- self.age=a
- def show (self):
- print self.name+"_" +str (self.age)
- AA = Person ("Jgood", 2)
- Aa.show ()
- F=open (' d:\\p.txt ',' W ')
- Pickle.dump (Aa,f,0)
- F.close ()
- #del person
- F=open (' d:\\p.txt ',' R ')
- Bb=pickle.load (f)
- F.close ()
- Bb.show ()
If the Del person is not commented out, then the error is as follows:
This means that the current module cannot find the definition of the class.
--------------------------------------------------
Clear_memo ()
Empty the Pickler "Memo". When serializing an object using an Pickler instance, it "remembers" the object reference that has already been serialized, so the dump (obj) is called multiple times for the same object, and Pickler is not "silly" to serialize multiple times.
Look at the following example:
[Python]View Plaincopy
- Import Stringio
- Import Pickle
- Class Person:
- def __init__ (self,n,a):
- self.name=n
- self.age=a
- def show (self):
- print self.name+"_" +str (self.age)
- AA = Person ("Jgood", 2)
- Aa.show ()
- Fle = Stringio.stringio ()
- Pick = pickle. Pickler (fle)
- Pick.dump (AA)
- Val1=fle.getvalue ()
- Print Len (val1)
- Pick.clear_memo ()
- Pick.dump (AA)
- Val2=fle.getvalue ()
- Print Len (val2)
- Fle.close ()
The above code runs as follows:
If it is not commented out, the result of the run is the first one. If commented out, the result of the run is the second one.
The main reason is that Python's pickle, if not clear_memo, will not serialize the object more than once.
Python, Pickle