---serialization of Python

Source: Internet
Author: User
Tags serialization

The process of converting any data type to a string is called serialization!

Why convert to a string? 1, do solid state storage 2, do network transmission

Python offers three ways to serialize: Json,pickle,shelve three types

JSON supports data types with tuple,list,dict

Pickle supports all Python data types

Import JSON

DiC = {"K": "V"}

Print (Type (DIC))---> Data type dictionary

Print (DIC)--->{' k ', ' V '}

Json_dict = Json.dumps (dic)-------> Dictionary to the process of the string, the process of serialization #dumps是和内存交互的

Print (Type (json_dic))---> Data type string

Print (json_dict)--->{"k": "V"}

Print (Json.loads (json_dict))---> The result is {' K ': ' V '}, the process of converting a string to another data type is deserialized

With open (file,mode= ' W ') as F:

Json.dump (dic,f) #dump is a file interaction

Two times dump into the file can not be a one-time load out, if you want to dump a number of data, not a data dump first, into a string, and then open the file, write into the file, add a carriage return \ n, read in accordance with the sign read out, or read, read it and then use loads

With open (file,mode= ' R ') as F:

Json.load (f) #从文件当中反序列化

With open (file, ' W ') as F:

Str_dic = Json.dump (DIC)

F.write (str_dic+ ' \ n ')

F.write (str_dic+ ' \ n ')

F.write (str_dic+ ' \ n ')

with open (file) as F:

For line in F:

Json.load (Line.strip ())

The use of pickle and JSON is identical, but the difference is that pickle can handle any data type including instantiated objects. But the file is written in a binary format, so the way to open the file is WB, the same time to read the file, using the Rb;pickle in the interaction with the file, can be multiple load

---serialization of Python

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.