json模塊python
pickle模塊json
shelve模塊網絡
序列化——將本來的字典、列表等內容轉換成一個字符串的過程就叫作序列化。數據結構
# 序列化模塊 # 數據類型轉化成字符串的過程就是序列化 # 爲了方便存儲和網絡傳輸 # json # dumps # loads # dump 和文件有關 # load load不能load屢次 # import json # data = {'username':['李華','二愣子'],'sex':'male','age':16} # json_dic2 = json.dumps(data,sort_keys=True,indent=4,separators=(',',':'),ensure_ascii=False) # print(json_dic2) # pickle #方法和json同樣 #dump和load的時候 文件是rb或者wb打開的 #支持python全部的數據類型 #序列化和反序列化須要相同的環境 # shelve # open方法 # open方法獲取了一個文件句柄 # 操做和字典相似
json特色:ui
1.只能處理簡單的可序列化的對象:this
json 能夠序列化的類型有 數字,字符串,列表,字典,元組也能夠用json序列化,不過是轉化成列表進行(load回來後也是列表)spa
2.json支持不一樣語言之間的數據交互3d
json提供了四個方法:dumps,loads 和 dump,loadcode
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'}]
import json f = open('json_file','w') dic = {'k1':'v1','k2':'v2','k3':'v3'} json.dump(dic,f) #dump方法接收一個文件句柄,直接將字典轉換成json字符串寫入文件 f.close() f = open('json_file') dic2 = json.load(f) #load方法接收一個文件句柄,直接將文件中的json字符串轉換成數據結構返回 f.close() print(type(dic2),dic2)
#json不支持屢次載入再出,若是須要,用如下這個思路 #dumps和loads多行 l = [{'k1':'111'},{'k2':'222'},{'k3':'3333'}] f = open('duohang','w') for i in l: f.write(json.dumps(i)+'\n') f.close()
import json #pickle能夠序列化python任何數據類型,好比集合 #json 能夠序列化的類型有 數字,字符串,列表,字典,元組也能夠用json序列化,不過是轉化成列表進行(load回來後也是列表) info = { 'name':'郭坤祥', 'age':19, 'job':'IT' } with open('序列化.txt','w',encoding='utf-8') as f: #f.write(json.dumps(info)) #整句話等價於 json.dump(info,f) json.dump(info,f,ensure_ascii=False) #要寫dump的時候文件裏顯示中文,須要加 ensure_ascii=False 這個參數 with open('序列化.txt','r',encoding='utf-8') as f2: # ret = json.loads(f2.read()) #整句話等價於 print(json.load(f2)) # print(type(ret),ret) print(json.load(f2)) dumps和loads是在內存中操做數據,dump和load必需要有文件纔可使用
import json f = open('file','w') json.dump({'國籍':'中國'},f) ret = json.dumps({'國籍':'中國'}) f.write(ret+'\n') json.dump({'國籍':'美國'},f,ensure_ascii=False) ret = json.dumps({'國籍':'美國'},ensure_ascii=False) f.write(ret+'\n') f.close()
Serialize obj to a JSON formatted str.(字符串表示的json對象) Skipkeys:默認值是False,若是dict的keys內的數據不是python的基本類型(str,unicode,int,long,float,bool,None),設置爲False時,就會報TypeError的錯誤。此時設置成True,則會跳過這類key ensure_ascii:,當它爲True的時候,全部非ASCII碼字符顯示爲\uXXXX序列,只需在dump時將ensure_ascii設置爲False便可,此時存入json的中文便可正常顯示。) If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity). indent:應該是一個非負的整型,若是是0就是頂格分行顯示,若是爲空就是一行最緊湊顯示,不然會換行且按照indent的數值顯示前面的空白分行顯示,這樣打印出來的json數據也叫pretty-printed json separators:分隔符,其實是(item_separator, dict_separator)的一個元組,默認的就是(‘,’,’:’);這表示dictionary內keys之間用「,」隔開,而KEY和value之間用「:」隔開。 default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. sort_keys:將數據根據keys的值進行排序。 To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
import json data = {'username':['李華','二愣子'],'sex':'male','age':16} json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False) print(json_dic2)
#json一次不能讀取多行,f.write(json.dumps(info)+'\n')
pickle和json用法同樣,也提供 dumps,loads,dump,load 四個方法
可是pickle在dumps的時候,是把數據存爲bytes數據類型
因此pickle在使用文件的時候用到的模式就是 wb和rb
pickle能夠序列化python任何數據類型,好比集合
json 能夠序列化的類型有 數字,字符串,列表,字典,元組也能夠用json序列化,不過是轉化成列表進行(load回來後也是列表)
pickle能夠分步dump和分佈load json就不行了
#pickle 分步序列 dic = {'k1':'v1','k2':'v2','k3':'v3'} str_dic = pickle.dumps(dic) print(str_dic) #一串二進制內容 dic2 = pickle.loads(str_dic) print(dic2) #字典 import time struct_time1 = time.localtime(1000000000) struct_time2 = time.localtime(2000000000) f = open('pickle_file','wb') pickle.dump(struct_time1,f) pickle.dump(struct_time2,f) f.close() f = open('pickle_file','rb') struct_time1 = pickle.load(f) struct_time2 = pickle.load(f) print(struct_time1.tm_year) print(struct_time2.tm_year) f.close()
shelve模塊是python3中新增的序列化模塊,日常pickle和json已經足以應付平常需求,故shelve比較少使用。
簡單用法以下:
import shelve f = shelve.open('shelve_file') f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'} #直接對文件句柄操做,就能夠存入數據 f.close() import shelve f1 = shelve.open('shelve_file') existing = f1['key'] #取出數據的時候也只須要直接用key獲取便可,可是若是key不存在會報錯 f1.close() print(existing) 注意shelve有個坑,在雖然開啓了只讀模式,可是仍是會更改對應的值 import shelve f = shelve.open('shelve_file', flag='r') existing = f['key'] ####### f['key'] = 50 #坑在這裏 print(existing) f.close() f = shelve.open('shelve_file', flag='r') existing2 = f['key'] f.close() print(existing2) import shelve f1 = shelve.open('shelve_file') print(f1['key']) f1['key']['new_value'] = 'this was not here before' f1.close() f2 = shelve.open('shelve_file', writeback=True) print(f2['key']) # f2['key']['new_value'] = 'this was not here before' f2.close()