json,用于各个平台语言的字符串 和 python数据类型间进行转换
json的方法:dumps,loads,dump,load
pickle-用于python特有的类型(字符串,列表,字典,集合等) 和 python的数据类型间进行转换
pickle的方法:dumps,loads,dump,load,但是都是以二进制存储
shelve,是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式#添加的key为字符串
1.json
1 #!/usr/bin/python 2 import json,pickle 3 ''' 4 json -用于字符串 和 python数据类型间进行转换 5 json 的操作 dump /dumps load /loads 6 pickle-用于python特有的类型 和 python的数据类型间进行转换 7 pickle模块提供了四个功能:dumps、dump、loads、load 8 ''' 9 test={"test_line1":"test_line1", "test_line2":"test_line2", "test_line3":"test_line3"} 10 x=json.dumps(test) 11 print(x) 12 print(json.loads(x)) 13 #dumps 写入文件 14 with open('json_test','w',encoding='utf-8')as f: 15 f.write(json.dumps(test)) 16 # 17 # 18 # # loads从文件读取 19 with open('json_test','r',encoding='utf-8') as f: 20 print(json.loads((f.read()))) 21 22 23 24 25 #dump 写入文件 26 with open('json_test','w',encoding='utf-8')as f: 27 json.dump(test,f) 28 # 29 # 30 # # load 从文件读取 31 with open('json_test','r',encoding='utf-8') as f: 32 print(json.load((f)))View Code
2.pickle
1 #!/usr/bin/python 2 import json,pickle 3 test={"test_line1":"test_line1", "test_line2":"test_line2", "test_line3":"test_line3"} 4 #dump 5 x=pickle.dumps(test) 6 print(x) 7 print(pickle.loads(x)) 8 9 with open('json_test.pk','wb')as f: 10 pickle.dump('test',f) 11 12 # 13 # # load 14 with open('json_test.pk','rb') as f: 15 print(pickle.load((f)))View Code
3.shelve
注意:打开文件后需要关闭文件
1 #!/usr/bin/python 2 # -*- coding: utf-8 -*- 3 import pickle,shelve 4 5 #shelve 写 6 shelve_test=shelve.open('shelve_test') #打开文件 7 name = 'test' #存字符串 8 list_test=[1,2,3,4,5] #存列表 9 dict_test={"test_line1":"test_line1", "test_line2":"test_line2", "test_line3":"test_line3"} #存字典 10 11 shelve_test['name']=name 12 shelve_test['dict_test']=dict_test #添加的key为字符串 13 shelve_test['list_test']=list_test 14 15 16 #shelve 读出来 17 print(shelve_test.get('name')) 18 print(shelve_test.get('list_test')) 19 print(shelve_test.get('dict_test')) 20 shelve_test.close()View Code
标签:python,print,json,shelve,test,pickle From: https://www.cnblogs.com/Little-Girl/p/17997086