What is serialization?
Converts an in-memory object to a linear structured string (sometimes called a byte stream) for storage or transmission. The behavior of this object into a string is often called serialization. Any data structure in memory can be mapped to a string.
Serialization of
function signature
#pickle.dump(objfile[, protocol])
The first attempt is to serialize the Table object to a file dBASE, written in byte form:
table = {‘a‘ : [123‘b‘ : [‘spam‘‘egg‘‘c‘ : {‘name‘‘Bob‘}}withopen(‘dbase‘‘wb‘as ff: pickle.dump(table, ff)
If we open this dBASE file, we can see some seemingly meaningless strings, in fact Python converts the Table object to such a string in the form of an internal contract. Note here that different versions of Python may be serialized differently, Serialization is therefore appropriate for storing data that is not particularly important. Otherwise, when you upgrade the Python version, deserialization can cause inconsistencies when restoring objects.
(dp0S‘a‘p1(lp2I1aI2aI3asS‘c‘p3(dp4S‘name‘p5S‘Bob‘p6ssS‘b‘p7(lp8S‘spam‘p9aS‘egg‘p10as.
It can also be serialized without writing to the file, and returned directly with Pickle.dump as a string:
string = pickle.dumps(table)
Deserialization
Function Signature:
pickle.load(file)
To read a deserialized restore object from a dBASE file:
withopen(‘dbase‘‘rb‘as fobj: table_ = pickle.load(fobj)print table_
Output:
{‘a‘: [123‘c‘: {‘name‘‘Bob‘‘b‘: [‘spam‘‘egg‘]}
It is not difficult to see from the output that the contents of the original table dictionary are the same.
Again we can read the string deserialization directly:
obj = pickle.loads(string)
Python serialization Pickle