Python modules commonly used - pickle & json serialization module

Python modules commonly used - pickle & json serialization module

First, what is serialized?

It refers to the sequence of the transition memory to a string data type, so that it can be stored to a hard disk or transmitted through the network to the remote, since the hard disk can only receive bytes or network transmission.

Second, why should serialize?

You play the game, playing tired, stop, turn off the game, I thought two days to play with. After two days, the game to resume where you left off, schedule your last game definitely saved on the hard drive, it is what form it? Many temporary data generated during the game is not regular, you might just have to turn off the game in the list of 10, three nested sets of data dictionary in memory, you need to survive, how do you keep? The list becomes a form file of rows and columns? That nest dictionary it? Simply can not exist. So, if there are ways to save directly to the memory data to the hard disk, and then start the next program, and then read back from the hard disk or the original format, then it is excellent.

Sequences for two of the modules:

  • json: python and for inter-string data type conversion.
  • pickle: python for converting between specific types and data types of the python.

pickle module provides four functions: dumps, dump, loads, load.

import pickle
data = {'k1':123,'k2':'Hello'}
# pickle.dumps 将数据通过特殊的形式转换为只有python语言认识的字符串
p_str = pickle.dumps(data)  # 注意dumps会把数据变成bytes格式
print(p_str)
# pickle.dump 将数据通过特殊的形式转换为只有python语言认识的字符串,并写入文件
with open('result.pk',"wb") as fp:
    pickle.dump(data,fp)
# pickle.load  从文件里加载
f = open("result.pk","rb")
d = pickle.load(f)
print(d)

json module also provides four functions: dumps, dump, loads, load. Usage is consistent with the pickle.

import json
# json.dumps 将数据通过特殊的形式转换位为所有程序语言都认识的字符串
j_str = json.dumps(data) # 注意json dumps生成的是字符串,不是bytes
print(j_str)
#dump入文件 
with open('result.json','w') as fp:
    json.dump(data,fp)
#从文件里load
with open("result.json") as f:
    d = json.load(f)
    print(d)

三、json  vs  pickle

json:

优点:跨语言(不同语言间的数据传递可用json交接)、体积小

缺点:只能支持int\str\list\tuple\dict

pickle:

优点:专为python设计,支持python所有的数据类型

缺点:只能在python中使用,存储数据占空间大

Guess you like

Origin www.cnblogs.com/Kwan-C/p/11620722.html