1. 程式人生 > >第二十二天- 序列化 pickle json shelve

第二十二天- 序列化 pickle json shelve

 

# 序列化:儲存或傳輸資料時,把物件處理成方便儲存和傳輸的資料格式,這個過程即為序列化
# Python中序列化的三種方案:
# 1.pickle python任意資料——》bytes寫入⽂件;寫好的bytes——》python的資料.
# 2.shelve 簡單另類的⼀種序列化⽅案. 可以作為⼀種⼩型的資料庫來使⽤
# 3.json 將字典列表轉換成字串,前後端資料互動高頻使用的⼀種資料格式


# pickle:
# 寫入到檔案的是bytes

# pickle中的dumps可以序列化⼀個物件.loads可以反序列化⼀個物件
 1 import pickle
2 class Cat: 3 def __init__(self,name,color): 4 self.name = name 5 self.color =color 6 7 def chi(self): 8 print("%s貓會吃老鼠"%(self.name)) 9 10 c = Cat("加菲","橘色") 11 # c.chi() 12 bs = pickle.dumps(c) # 把物件轉換成bytes 13 # print(bs) # b'\x80\x03c__main__\nCat\nq\x00)\x81q\x01}q\x02(X\x04\x00\x00\x00nameq\x03X\x06\x00\x00\x00\xe5\x8a\xa0\xe8\x8f\xb2q\x04X\x05\x00\x00\x00colorq\x05X\x06\x00\x00\x00\xe6\xa9\x98\xe8\x89\xb2q\x06ub.'
14 15 # 把bytes反序列化成物件 16 cc = pickle.loads(b'\x80\x03c__main__\nCat\nq\x00)\x81q\x01}q\x02(X\x04\x00\x00\x00nameq\x03X\x06\x00\x00\x00\xe5\x8a\xa0\xe8\x8f\xb2q\x04X\x05\x00\x00\x00colorq\x05X\x06\x00\x00\x00\xe6\xa9\x98\xe8\x89\xb2q\x06ub.') 17 cc.chi() 18 print(cc.name,cc.color) # 加菲貓會吃老鼠 加菲 橘色

# dump load讀寫檔案操作
# dump load ⼀個物件寫讀到檔案
1 c = Cat("加菲","橘色")
2 pickle.dump(c,open("cat.dat",mode = 'wb'))  # 把物件寫到檔案  pickle.dump() 注意bytes用wb模式
3 ccc = pickle.load(open('cat.dat',mode='rb'))  # 把物件讀取出來  pickle.load() 注意bytes用rb模式
4 ccc.chi()  # 加菲貓會吃老鼠
5 print(ccc.name,ccc.color)  # 加菲 橘色

# pickle用list讀寫多個物件
 1 c1 = Cat("加菲1","橘色")
 2 c2 = Cat("加菲2","橘色")
 3 c3 = Cat("加菲3","橘色")
 4 c4 = Cat("加菲4","橘色")
 5 c5 = Cat("加菲5","橘色")
 6 
 7 # lst = [c1,c2,c3,c4,c5]
 8 # f = open('cat.dat',mode='wb')
 9 # pickle.dump(lst,f)  # 把lst寫到f
10 
11 f = open('cat.dat',mode='rb')
12 lis = pickle.load(f)  # 把lis從f讀取出來
13 for cc in lis:
14     cc.chi()

# 應用:pickle實現註冊登入
 1 import pickle
 2 
 3 
 4 class User:
 5     def __init__(self,username,password):
 6         self.username = username
 7         self.password = password
 8 
 9 
10 class Client:
11     # 註冊
12     def regist(self):
13         uname = input("請輸入你的賬戶:")
14         pwd = input("請輸入你的密碼:")
15         user = User(uname,pwd)  # 把uname pwd 傳參到User類
16         pickle.dump(user,open("userinfo",mode='ab'))  # 把物件儲存到userinfo
17         print("註冊成功!")
18 
19     # 登入
20     def login(self):
21         uname = input("請輸入你的賬戶:")
22         pwd = input("請輸入你的密碼:")
23         f = open('userinfo',mode='rb')  
24         while 1:
25             # 加入try except 當不存在的賬戶登入時 丟擲錯誤
26             try:
27                 u = pickle.load(f)  # 從userinfo中讀取出使用者 
28                 if u.username == uname and u.password == pwd:
29                     print("登陸成功!")
30                     break
31             except Exception as e:
32                 print("登入失敗!")
33                 break
34 
35 d = Client()
36 # print("註冊")
37 # d.regist()
38 # d.regist()
39 # d.regist()
40 # print("登入")
41 # d.login()
42 # d.login()
43 # d.login()
View Code


# shelve 就是把資料寫到硬碟上.操作shelve非常的像操作字典.
1 import shelve
2 
3 d = shelve.open("test")  # 可理解成檔案型別的字典
4 # d['wf'] = '汪峰'
5 d['wf'] = '王菲'
6 print(d['wf'])  # 汪峰  王菲
7 d.close()
# 儲存一些複雜點的資料
 1 import shelve
 2 d = shelve.open('test')
 3 d['wf'] = {'name':'汪峰','age':47,'wife':{'name':'章子怡','hobby':'拍電影'}}
 4 print(d['wf']) # 執行結果 {'name': '汪峰', 'age': 47, 'wife': {'name': '章子怡', 'hobby': '拍電影'}}
 5 d.close()
 6 
 7 # 嘗試修改
 8 d = shelve.open('test')
 9 d['wf']['wife']['name'] = '小章'
10 print(d['wf'])  # 執行結果 {'name': '汪峰', 'age': 47, 'wife': {'name': '章子怡', 'hobby': '拍電影'}}
11 d.close()
12 # 坑 由上可知 直接修改沒效果 需用到 writeback
# writeback=True 可動態的把修改的資訊寫入到⽂件中.
1 d = shelve.open('test',writeback=True)  # 檔案型別字典修改時 writeback 把修改回寫到檔案
2 d['wf']['wife']['hobby'] = '搓麻將'  # 修改vlue
3 d.close()
4 
5 d = shelve.open('test')
6 print(d['wf'])  # 執行結果 {'name': '汪峰', 'age': 47, 'wife': {'name': '章子怡', 'hobby': '搓麻將'}}
7 d.close()

continue...