Import Pickle
data = {' K1 ': 123, ' K2 ': 888}
Print (type data) #<class ' Dict ' >
#dumps可以将数据类型转换成只有python才认识的字符串
P_STR = pickle.dumps (data)
Print (P_STR) #结果b ' \x80\x03}q\x00 (x\x02\x00\x00\x00k1q\x01k{x\x02\x00\x00\x00k2q\x02mx\x03u. ')
Print (Type (P_STR)) #结果 <class ' bytes ' >
With open (' Data.pkl ', ' WB ') as F:
Pickle.dump (data, F)
#同样读取的时候也需要打开文件
With open (' data.pkl ', ' RB ') as F:
Data_1 = Pickle.load (f)
Print (data_1) #结果: {' K2 ': 888, ' K1 ': 123}
Print (Type (data_1)) #结果 <class ' dict ' >
This is the two modules used for serialization:
? JSON: for converting between string and Python data types
Pickle: conversion between Python-specific types and Python data types
The Json module provides four functions: dumps, dump, loads, load
The Pickle module provides four functions: dumps, dump, loads, load
Simple use of pickle and simple comparison of JSON