1. 程式人生 > >序列化 json pickle

序列化 json pickle

序列化 把物件打散成二進位制位元組 bytes
1. pickle 把一個物件轉化成bytes寫入到檔案
pickle.dumps() 把物件轉換成bytes
pickle.loads() 把bytes轉化成物件

pickle.dump() 把物件轉換成bytes. 寫入到檔案
pickle.load() 把檔案中的bytes讀取. 轉化成物件

2. shelve 小型資料庫, redis, mongodb, dict
當成字典來用
writeback=True

import shelve

# d = shelve.open("sylar") # 檔案型別的字典
# d['wf'] = "汪峰"
# d.close()
#
# d = shelve.open("sylar")
# print(d['wf'])
# d.close()

# d = shelve.open("sylar") # 檔案型別的字典
# d['wf'] = {"name":"汪峰", "age": 18, "wife":{"name":"章子怡", "hobby":"拍電影"}}
# d.close()

# d = shelve.open("sylar", writeback=True) # 檔案型別的字典 wirteback把修改的內容自動的回寫到檔案中
# d['wf']['wife']['hobby'] = "當導師" # 改
# d.close()

# d = shelve.open("sylar") # 檔案型別的字典
# print(d['wf'])
# d.close()

3. json 以前用xml 先在用json
json.dumps() 把字典轉換成json字串
json.loads() 把json字串轉化成字典

json.dump() 把字典轉換成json字串. 寫入到檔案
json.load() 把檔案中的json字串讀取. 轉化成字典

dic1 = {"name":'毒液', "評分": "0.9"}
dic2 = {"name":'與神同行', "評分": "10"}
dic3 = {"name":'看不見的客人', "評分": "9.5"}

# lst = [dic1, dic2, dic3]
# f = open("movie.json", mode="w", encoding="utf-8")
# for d in lst:
# s = json.dumps(d, ensure_ascii=False)
# f.write(s+"\n")

# f = open("movie.json", mode="r", encoding="utf-8")
# dic1 = json.load(f) # 當json檔案中儲存多個json的時候不能一次性全部都讀取出來
# print(dic1)

default = 把物件轉化成字典. 需要自己寫轉換過程
object_hook = 把字典轉化成物件. 需要自己寫轉換過程

ensure_ascii = False 可以處理中文

# # 準備一個字典
# dic = {"a": "小蘿莉", "b": "大蘿莉", "c": "猥瑣大叔", "d": False, "e": None}
# # python中可以直接把字典或者列表轉化成json
# s = json.dumps(dic, ensure_ascii=False) # pickle
# print(type(s))
# print(s)

# s = '{"a": "小蘿莉", "b": "大蘿莉", "c": "猥瑣大叔", "d": false, "e": null}'
# d = json.loads(s) # 把json轉化成字典
# print(d)
# print(type(d))


4. configparser 處理windows配置檔案的 dict