第二十一天 PYTHON學習
【今日學習】
一、什麽是序列化?
我們把對象(變量)從內存中變成可存儲或傳輸的過程稱之為序列化,在Python中叫pickling,在其他語言中也被稱之為serialization,marshalling,flattening等等,都是一個意思。
二、為什麽要序列化?
1:持久保存狀態【硬盤存】
需知一個軟件/程序的執行就在處理一系列狀態的變化,在編程語言中,‘狀態‘會以各種各樣有結構的數據類型(也可簡單的理解為變量)的形式被保存在內存中。
內存是無法永久保存數據的,當程序運行了一段時間,我們斷電或者重啟程序,內存中關於這個程序的之前一段時間的數據(有結構)都被清空了。
在斷電或重啟程序之前將程序當前內存中所有的數據都保存下來(保存到文件中),以便於下次程序執行能夠從文件中載入之前的數據,然後繼續執行,這就是序列化。
具體的來說,你玩使命召喚闖到了第13關,你保存遊戲狀態,關機走人,下次再玩,還能從上次的位置開始繼續闖關。或如,虛擬機狀態的掛起等。
2:跨平臺數據交互【網絡傳】
序列化之後,不僅可以把序列化後的內容寫入磁盤,還可以通過網絡傳輸到別的機器上,如果收發的雙方約定好實用一種序列化的格式,那麽便打破了平臺/語言差異化帶來的限制,實現了跨平臺數據交互。
反過來,把變量內容從序列化的對象重新讀到內存裏稱之為反序列化,即unpickling。
json模塊【轉化成str類型】(優先掌握)
序列化與反序列化一:
json.dumps json.loads 是一對
序列化:
dic={‘name‘:‘egon‘,‘age‘:18}
with open(‘db.json‘,‘w‘,encoding=‘utf-8‘) as f:
res = json.dumps(dic)
f.write(res)
print(res,type(res))
結果
{"name": "egon", "age": 18} <class ‘str‘>
#json格式全都是雙引號,如果不是雙引號,反序列化json就識別不了
#一個數據結構dump一次就行了,不要用‘a.txt ’去添加
反序列化:
with open(‘db.json‘,‘r‘,encoding=‘utf-8‘) as f:
data=f.read()
res=json.loads(data)
print(res)
結果
{‘name‘: ‘egon‘, ‘age‘: 18}
序列化與反序列化二:
簡化版
json.dump json.load 是一對
序列化
import json
dic = {‘name‘: ‘egon‘, ‘age‘: 18}
with open(‘db1.json‘,‘w‘,encoding=‘utf-8‘) as f:
json.dump(dic,f)
反序列化
import json
dic = {‘name‘: ‘egon‘, ‘age‘: 18}
with open(‘db1.json‘,‘r‘,encoding=‘utf-8‘) as f:
print(json.load(f))
優點:數據跨平臺較好
缺點:有些python數據類型不能識別,只能識別以下圖片上數據類型
沒有元組和集合
pickle模塊(了解)【轉化成bytes類型】
把所有的數據類型存成bytes類型,讀也需要用bytes類型去讀
優點:能識別所有python數據類型,能把所有數據類型序列化,用法與json類似
缺點:也是最致命缺點,只能識別python,跨平臺較差
# 用戶註冊後得到的數據
name = "高跟"
password = "123"
height = 1.5
hobby = ["吃","喝","賭","飄",{1,2,3}]
# with open("userdb.txt","wt",encoding="utf-8") as f:
# text = "|".join([name,password,str(height)])
# f.write(text)
# pickle支持python中所有的數據類型
user = {"name":name,"password":password,"height":height,"hobby":hobby,"test":3}
# 序列化的過程
# with open("userdb.pkl","ab") as f:
# userbytes = pickle.dumps(user)
# f.write(userbytes)
# 反序列化過程
# with open("userdb.pkl","rb") as f:
# userbytes = f.read()
# user = pickle.loads(userbytes)
# print(user)
# print(type(user))
#
#dump 直接序列化到文件
# with open("userdb.pkl","ab") as f:
# pickle.dump(user,f)
# #load 從文件反序列化
with open("userdb.pkl","rb") as f:
user = pickle.load(f)
print(user)
shelve模塊(了解)
也能像pickle序列化所有python數據類型,比pickle更方便
info1={‘name‘:‘egon‘,‘age‘:18}
info2={‘name‘:‘run‘,‘age‘:19}
import shelve
d=shelve.open(‘db.shv‘)
d[‘egon‘]=info1
d[‘run‘]=info2
d.close()
import shelve
d=shelve.open(‘db.shv‘)
# d[‘egon‘]
# d[‘run‘]
print(d[‘egon‘])
print(d[‘run‘])
import shelve
d=shelve.open(‘db.shv‘,writeback=True)
d[‘egon‘][‘age‘]=20
d[‘run‘][‘age‘]=18
print(d[‘egon‘])
print(d[‘run‘])
xml模塊(了解)
古老的用法
也是將內存中數據儲存起來或傳輸出去,將數據組織起來
# 查
# 三種查找節點的方式
# 第一種
# import xml.etree.ElementTree as ET
# tree=ET.parse(‘a.xml‘)
# root=tree.getroot()
# res=root.iter(‘year‘)
# # 會在整個樹中查找,而且是查找所有
# print(res)
# for item in res:
# print(‘*********************‘)
# print(item.tag)
# print(item.attrib)
# print(item.text)
# 第二種:
# res=root.find(‘country‘)
# # 只能在當前元素下一級查找,並且找到一個就結束
# print(item.tag)
# print(item.attrib)
# print(item.text)
# 第三種
# cy=root.findall(‘country‘)只能在當前元素下一級查找
# # print(cy)
# for item in cy:
# print(item.tag)
# print(item.attrib)
# print(item.text)
# 改:
# import xml.etree.ElementTree as ET
# tree=ET.parse(‘a.xml‘)
# root=tree.getroot()
# for year in root.iter(‘year‘):
# year.text=str(int(year.text)+10)
# year.attrib={‘update‘:‘year‘}
# tree.write(‘a.xml‘)
# # 增
# import xml.etree.ElementTree as ET
# tree=ET.parse(‘a.xml‘)
# root=tree.getroot()
# for country in root.iter(‘country‘):
# year=country.find(‘year‘)
# if int(year.text)> 2020:
# print(country.attrib)
# ele=ET.Element(‘run‘)
# ele.attrib={‘nb‘:‘shuai‘}
# ele.text=‘ok‘
# country.append(ele)
# tree.write(‘a.xml‘)
# 刪
# import xml.etree.ElementTree as ET
# tree=ET.parse(‘a.xml‘)
# root=tree.getroot()
# for country in root.iter(‘country‘):
# year=country.find(‘year‘)
# if int(year.text)> 2020:
# # print(country.attrib)
# country.remove(year)
# tree.write(‘a.xml‘)
configparser模塊
import configparser
# 取值
# import configparser
# config=configparser.ConfigParser()
# config.read(‘my.ini‘)
# secs=config.sections()
# print(secs)
# print(config.options(‘run‘))
#
# print(config.get(‘run‘,‘age‘))
# print(config.getboolean(‘run‘,‘is_husband‘))
# print(config.getfloat(‘run‘,‘salary‘))
【今日領悟】
1.json是最常用的序列化與反序列化模塊,其它類型的模塊常用部分熟悉就行
2.需要在實際按例中去應用才能體會這幾個模塊的不同
第二十一天 PYTHON學習