模块的补充
序列化模塊
序列化:就是把其它類型的數(shù)據(jù)類型轉(zhuǎn)換成 字符串 bytes 的過程
json模塊 ? 不支持連續(xù)的讀和寫
import json
?
dumps ?loads 用法
dic = {'key':'v1','key2':'v2'} import json ret = json.dumps(dic) print(ret,type(ret)) #{"key": "value", "key2": "value2"} <class 'str'> 序列化
ret1 = json.loads(ret)
print(ret1,type(ret1))
#{'key':'v1','key2':'v2'}<class 'dict'> 反序列化
dumps ?dump?向文件中記錄字典的用法
dic = {'key' : 'value','key2' : 'value2'} ret = json.dumps(dic) #轉(zhuǎn)化成字符串類型 with open('lilili','a') as f: #將轉(zhuǎn)化后的添加到 lilili 這個文件中,沒有自己建立 f.write(ret)dumpdic = {'key' : 'value','key2' : 'value2'} with open('lilili','a') as f:json.dump(dic,f) #直接寫入文件中#json.dump(寫入的內(nèi)容,寫入到哪個文件)loads ?load 文件讀取的用法
with open('lilili','r') as f:str_dic = f.read() dic = json.loads(str_dic) print(dic.keys()) #{'key','key1'} with open('lilili','r') as f:dic = json.load(f) print(dic.keys()) #{'key','key1'}?
pickle模塊
pickle支持在 python 中幾乎所有的數(shù)據(jù)類型
可以多次dump和load
dumps ?loads
?
dic = {(1,2,3):{'a','b'},1:'abc'} ret = pickle.dumps(dic) print(ret) #輸出的是字節(jié) ret1 = pickle.loads(ret) print(ret1) # #{(1,2,3):{'a','b'},1:'abc'}dump,load
dic = {(1,2,3):{'a','b'},1:'abc'} with open('nihao','wb') as f:pickle.dump(dic,f)#把dic字典添加到 nihao 這個文件里了,因為是字節(jié),所以說寫用 wb,下面同理 with open('nihao','rb') as f:rey = pickle.load(f)print(rey) #{(1,2,3):{'a','b'},1:'abc'}?
轉(zhuǎn)載于:https://www.cnblogs.com/lzqrkn/p/9513399.html
總結(jié)
- 上一篇: ES6 generator
- 下一篇: invalid character fo