Home >Backend Development >Python Tutorial >A brief introduction to Python's serialization and deserialization modules (example code)

A brief introduction to Python's serialization and deserialization modules (example code)

不言
不言Original
2018-09-14 16:55:361970browse

This article brings you a brief introduction (example code) about Python's serialization and deserialization modules. It has certain reference value. Friends in need can refer to it. I hope it will help You helped.

Serialization: The conversion process of converting an object into a data format that can be transmitted over the network or stored on a local disk is called serialization, and vice versa is called deserialization

json: used to realize direct information interaction between different languages ​​and different programs. json supports serialization between all high-level languages Interaction, json can only be converted through the format of Dictionary->String->Dictionary

Note: json is a read-write serialization format

pickle: A unique serialization method in python. If necessary, Python can serialize and convert almost all types in Python

Note: pickle is a binary read-write sequence Format

json and pickle have the same method:

x.dumps(): will get json or pickle dataSerialize into a bytes, then write the bytes to disk or transmit

When data is read from disk into memory, the content is first read into bytes, and then used loadsDeserializationOut of the object

 x.dump( ): You can directly serialize the obtained json or pickle data and save it to the file

## x.load(): You can directly read the json in the file Or pickle data for

Deserialization

Example:

Serialization


import json,pickle
# f = open('测试文件.txt', 'w')     # json 运用 'w',写入
f = open('测试文件.txt', 'wb')        # pickle 运用二进制'wb'写入

info = {
    'Presly': 'come on',
    'Vera': '2333',
    'mini': 'hello'
}
# json.dump(info, f)        # 转为纯字符串
# f.write(json.dumps(info))

pickle.dump(info, f)         # 转为二进制
# f.write(pickle.dumps(info))

f.close()
Deserialization

import json , pickle
# f = open('测试文件.txt', 'r')
f = open('测试文件.txt', 'rb')
# data = json.load(f)         # 只能识别字符串,不能识别二进制
# data = json.loads(f.read())
# data = pickle.load(f)          # 只能识别二进制
data = pickle.loads(f.read())
print(data)
f.close()

Related recommendations:

python3 serialization and deserialization usage examples

Detailed introduction to serialization and deserialization

The above is the detailed content of A brief introduction to Python's serialization and deserialization modules (example code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn