json模块:是所有语言公认的一种序列/特殊的字符串;但是支持的python数据类型有限,其中包括:int、str、bool、dict、list、tuple、None、float、Turn、False。
- json模块的使用
import json
- dumps,loads --- 主要用于网络传输,也可以用于文件的存取(可以是单个,也可以是多个)
import json
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = json.dumps(dic) #序列化:将一个字典转换成一个特殊字符串
print(type(str_dic),str_dic) #<class 'str'> {"k3": "v3", "k1": "v1", "k2": "v2"}
#注意,json转换完的字符串类型的字典中的字符串是由""表示的
dic2 = json.loads(str_dic) #反序列化:将一个特殊字符串格式的字典转换成一个字典
#注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
print(type(dic2),dic2) #<class 'dict'> {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
例:
list_dic = [1,['a','b','c'],3,{'k1':'v1','k2':'v2'}]
str_dic = json.dumps(list_dic) #也可以处理嵌套的数据类型
print(type(str_dic),str_dic)
#<class 'str'> [1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]
list_dic2 = json.loads(str_dic)
print(type(list_dic2),list_dic2)
#<class 'list'> [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]
# 特殊的参数:
dic = {'username':'太白','password':'123','status':'False'}
SRT_DIC = json.dumps(dic)
str_dic = json.dumps(dic,ensure_ascii=False,sort_keys=True)
# ensure_ascii=False 将中文显示出来
# sort_keys=True 排序
print(SRT_DIC)
print(str_dic)
演示1.
# dic = {'username': '太白', 'password': '123', 'status': 'False'}
# set1 = json.dumps(dic)
# with open("存储.json",mode="w",encoding='utf-8') as f1:
# f1.write(set1)
# with open("存储.json",encoding='utf-8') as f2:
# set2 = f2.read()
# print(json.loads(set2))
dic = {'username': '太白', 'password': '123', 'status': 'False'}
a = json.dumps(dic,ensure_ascii=False,sort_keys=True) # 将中文显示出来并排序
with open("练习1.json","w",encoding='utf-8') as a1:
a1.write(a)
with open("练习1.json",encoding="utf-8") as a2:
b = a2.read()
print(json.loads(b))
- dump,load --- 单个数据的存取文件
pickle模块:只能在python语言使用的一种序列化模块;支持python中所有的数据类型对象。
- pickle模块的使用
import pickle
代码示例:
import pickle
# dumps,loads 只能网络传输
li = ['李白','杜甫','白居易',666]
ret = pickle.dumps(li)
print(ret)
print(type(ret))
l2 = pickle.loads(ret)
print(l2,type(l2))
# dump,load 数据结构存取文件
li = ['李白','杜甫','白居易',666]
with open("pickle练习.pickle",mode = 'wb') as f1:
pickle.dump(li,f1)
with open("pickle练习.pickle",mode = 'rb') as f2:
ret = pickle.load(f2)
print(ret,type(ret))
多个文件写入数据:
l1 = ['李白','杜甫','白居易',111]
l2 = ['李白','杜甫','白居易',222]
l3 = ['李白','杜甫','白居易',333]
with open("pickle练习.pickle",mode = 'wb') as f1:
pickle.dump(l1,f1)
pickle.dump(l2,f1)
pickle.dump(l3,f1)
with open("pickle练习.pickle",mode = 'rb') as f1:
ret1 = pickle.load(f1)
ret2 = pickle.load(f1)
ret3 = pickle.load(f1)
print(ret1,ret2,ret3)
pickle模块的练习:
def func():
for i in range(3):
print(i)
print('in func!')
with open('pickle练习.pickle',mode='wb') as f1:
pickle.dump(func,f1)
with open('pickle练习.pickle',mode='rb') as f1:
ret = pickle.load(f1)
ret()