-
json
在不同的编程语言之间传递对象
1 dic = {‘name‘: ‘alvin‘, ‘age‘: 23, ‘sex‘: ‘male‘} 2 print(type(dic)) # <class ‘dict‘> 3 4 j = json.dumps(dic) 5 print(type(j)) # <class ‘str‘> 6 7 f = open(‘序列化对象‘, ‘w‘) 8 f.write(j) # -------------------等价于json.dump(dic,f) 9 f.close() 10 # -----------------------------反序列化<br> 11 import json 12 13 f = open(‘序列化对象‘) 14 data = json.loads(f.read()) # 等价于data=json.load(f) 15 16 import json 17 #dct="{‘1‘:111}"#json 不认单引号 18 #dct=str({"1":111})#报错,因为生成的数据还是单引号:{‘one‘: 1} 19 20 dct=‘{"1":"111"}‘ 21 print(json.loads(dct)) 22 23 #conclusion: 24 # 无论数据是怎样创建的,只要满足json格式,就可以json.loads出来,不一定非要dumps的数据才能loads
-
pickle
pickle是python自己的序列化,想序列化什么就序列化什么,不像json有限制。
import pickle dic = {‘name‘: ‘alvin‘, ‘age‘: 23, ‘sex‘: ‘male‘} print(type(dic)) # <class ‘dict‘> j = pickle.dumps(dic) print(type(j)) # <class ‘bytes‘> f = open(‘序列化对象_pickle‘, ‘wb‘) # 注意是w是写入str,wb是写入bytes,j是‘bytes‘ f.write(j) # -------------------等价于pickle.dump(dic,f) f.close() # -------------------------反序列化 import pickle f = open(‘序列化对象_pickle‘, ‘rb‘) data = pickle.loads(f.read()) # 等价于data=pickle.load(f) print(data[‘age‘])
-
shelve模块
shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型
import shelve f=shelve.open(r‘sheve.txt‘) # f[‘stu1_info‘]={‘name‘:‘egon‘,‘age‘:18,‘hobby‘:[‘piao‘,‘smoking‘,‘drinking‘]} # f[‘stu2_info‘]={‘name‘:‘gangdan‘,‘age‘:53} # f[‘school_info‘]={‘website‘:‘http://www.pypy.org‘,‘city‘:‘beijing‘} print(f[‘stu1_info‘][‘hobby‘]) f.close()
时间: 2024-10-27 13:57:05