1.json模块
功能:将其他形式的数据类型转化为json字符串类型,将json字符串转化为其他对应的数据类型
方法:json.dumps() 作用:将所有单引号变成双引号;将所有数据类型变成字符串
import json
dic = {"name":"sb","age":18}
a = json.dumps(dic)
print(type(a),a)
f = open("newfile","w")
f.write(a)=======>将数据写入新文件
f.close()
>>>> <class 'str'> {"name": "sb", "age": 18}
json.loads()作用:将json子字符串数据还原成之前类型
import json
f_read = open("newfile","r")
date = json.loads(f_read.read())
print(type(date),date)
f_read.close()
>>>> <class 'dict'> {'name': 'sb', 'age': 18}
2.pickle模块----序列化和反序列化
方法:pickle.dumps() pickle.loads()
import pickle
dic = {"name":"sb","age":18}
a = pickle.dumps(dic) #将字典类型的数据转化为字节序列
f = open("序列化对象_pickle","wb") #新建的文件不能读出来,和json不同
f.write(a)
f.close()
>>> <class 'bytes'> b'x80x03}qx00(Xx04x00x00x00nameqx01Xx02x00x00x00sbqx02Xx03x00x00x00ageqx03K{u.'
import pickle
f = open("序列化对象_pickle","rb")
date = pickle.loads(f.read())
print(date["age"])
>>> 18