python 序列化
程序员文章站
2022-04-21 18:15:46
序列化 1、json模块 2、pickle模块 3、shelve模块 ......
序列化
1、json模块
2、pickle模块
3、shelve模块
#-----json模块-----
#----将字典存储到文本dumps()方法
1 import json 2 3 #实例1 dumps() 4 a = {'name':'dream','age':'18'} 5 a = json.dumps(a) #dumps 加载进去 6 with open('json_test.json','w') as f: 7 f.write(a) 8 f.close() 9 10 #实例2 dump() 11 a = {'name':'dream','age':'18'} 12 with open('json_test2.json','w') as f: 13 json.dump(a,f) 14 f.close()
#------将文本读取loads()方法
1 import json 2 3 #实例1 loads() 4 with open('json_test.json','r') as f: 5 a = f.read() 6 a = json.loads(a) 7 print(a['name']) #dream 8 f.close() 9 #实例2 load() 10 with open('json_test2.json','r') as f: 11 12 a = json.load(f) 13 print(a['name']) #dream 14 f.close()
#-----pickle模块-----
#python内部数据转换
#将函数写入文本 dumps() 方法
1 import pickle 2 3 def foo(): 4 print('python') 5 6 a = pickle.dumps(foo) 7 with open('pickle_test','wb') as f: 8 f.write(a) 9 f.close()
#将文本读取loads()
1 import pickle 2 3 def foo(): #需要将函数同时复制一份 4 print('python') 5 6 with open('pickle_test','rb') as f: 7 a = f.read() 8 a = pickle.loads(a) 9 a() 10 f.close()
#-----shelve模块-----
1 import shelve 2 3 f = shelve.open(r'shelve_test.txt') 4 # r python源生字符串,d:\\abc.txt 容易在读取文件时容易产生歧义(报错无法读取) 5 6 f['info']={'name':'yzz','age':'26'} 7 f['shopping'] = {'name':'dream','age':'20'} 8 9 date = f.get('info') #获取文件内容 10 date1 =f.get('shopping') 11 print(date) 12 print(date1['name'])