Python serialization Pickle

Source: Internet
Author: User
Tags dbase

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.