1. 程式人生 > >Python 21 常用模組02

Python 21 常用模組02

常用模組02

1. 什麼是序列化

  • 在python中存在三種序列化的方案
  1. pickle. 可以將我們python中的任意資料型別轉化成bytes並寫入到⽂件中. 同樣也可以把檔案中寫好的bytes轉換回我們python的資料. 這個過程被稱為反序列化
  2. shelve. 簡單另類的一種序列化的方案.
  3. json. 將python中常用的字典, 列表轉化成字串. 是目前前後端資料互動使用頻率最高的一種資料格式.

2. pickle(重點)

python物件寫入到檔案中的一種解決⽅案.但是寫入到檔案的是bytes

import pickle
class Cat:
 def __init__(self, name, age):
 self.name = name
 self.age = age
 def catchMouse(self):
 print(self.name, "抓老鼠")
 c = Cat("jerry", 18)
bs = pickle.dumps(c) # 序列化一個物件.
print(bs) # ⼀堆⼆進位制. 看不懂
cc = pickle.loads(bs) # 把二進位制反序列化成我們的物件
cc.catchMouse() # 貓依然是貓. 還可以抓老鼠
  • pickle中的dumps可以序列化一個物件.
  • loads可以反序列化一個物件.
  • dump還可以直接 把一個物件寫入到檔案中

3. shelve

shelve提供python的持久化操作

import shelve
shelf = shelve.open("sylar")
# shelf["jay"] = "周杰倫"
print(shelf['jay'])
shelf.close()
s = shelve.open("sylar")
# s["jay"] = {"name":"周杰倫", "age":18, "hobby":"哄小孩"}
print(s['jay'])
s.close()

下面是測試

s = shelve.open("sylar")
s['jay']['name'] = "胡辣湯" # 嘗試改變字典中的資料
s.close()
s = shelve.open("sylar")
print(s['jay']) # 並沒有改變
s.close()
解決方案:
s = shelve.open("sylar", writeback=True)
s['jay']['name'] = "胡辣湯" # 嘗試改變字典中的資料
s.close()
s = shelve.open("sylar")
print(s['jay']) # 改變了.
s.close()

writeback=True可以動態的把我們修改的資訊寫入到檔案中

s = shelve.open("sylar", writeback=True)
del s['jay']
s.close()
s = shelve.open("sylar")
print(s['jay']) # 報錯了, 沒有了
s.close()
s = shelve.open("sylar", writeback=True)
s['jay'] = "周杰倫"
s['wlj'] = "王力巨集"
s.close()
s = shelve.open("sylar")
for k in s: # 像字典那樣遍歷
 print(k)
print(s.keys()) # 拿到所有key的集合
for k in s.keys():
print(k)
for k, v in s.items(): # 像字典一樣操作
print(k, v)
s.close()

4. json(重點)

# ----- loads  轉換字串到json ----------------
s1 = '{"1":"毒液","2":"雷神","3":"海王","4":false,"5":null}'
d = json.loads(s1)
print(d)
# --------------字串 轉 字典  進檔案----------------

dic1 = {"1":"毒液","2":"雷神","3":"海王","4":False,"5":None,"6":{"想看":"沒錢","能看":"沒時間"}}
f = open("du.json",mode="w",encoding="utf-8")
json.dump(dic1,f,ensure_ascii=False,indent=4)
f = open("du.json",mode="r",encoding="utf-8")
d = json.load(f)
print(d)
# -------------json  函式傳入返回 字典形式---------
class Man():
    def __init__(self,firstname,lastname):
        self.firstname = firstname
        self.lastname = lastname

Person = Man("海格力斯","王五")

def func(obj):
    return {
        "first":obj.firstname,
        "last":obj.lastname
    }
s = json.dumps(Person,default=func,ensure_ascii=False)
print(s)
#-----------------字串 字典 返回  物件------------
class Man():
    def __init__(self,firstname,lastname):
        self.firstname = firstname
        self.lastname = lastname
dic = '{"firstname":"海格力斯","lastname":"王五"}'
def func(dic):
    return Man(dic["firstname"],dic["lastname"])

s = json.loads(dic,object_hook=func)
print(s.firstname)