Python3.5內(nèi)置模塊之shelve模塊、xml模塊、configparser模塊、hashlib、hmac模塊用法分析
本文實(shí)例講述了Python3.5內(nèi)置模塊之shelve模塊、xml模塊、configparser模塊、hashlib、hmac模塊用法。分享給大家供大家參考,具體如下:
1、shelve模塊
shelve類(lèi)似于一個(gè)key-value數(shù)據(jù)庫(kù),可以很方便的用來(lái)保存Python的內(nèi)存對(duì)象,其內(nèi)部使用pickle來(lái)序列化數(shù)據(jù),
簡(jiǎn)單來(lái)說(shuō),使用者可以將一個(gè)列表、字典、或者用戶自定義的類(lèi)實(shí)例保存到shelve中,下次需要用的時(shí)候直接取出來(lái),
就是一個(gè)Python內(nèi)存對(duì)象,不需要像傳統(tǒng)數(shù)據(jù)庫(kù)一樣,先取出數(shù)據(jù),然后用這些數(shù)據(jù)重新構(gòu)造一遍所需要的對(duì)象。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:ZhengzhengLiu import shelve import datetime d = shelve.open('shelve_test') # 打開(kāi)一個(gè)文件 info = { "age":23, "job":"IT" } name = ["alex", "rain", "test"] d["name"] = name # 持久化列表 d["info"] = info # 持久化字典 d["data"] = datetime.datetime.now() d.close()
運(yùn)行結(jié)果:產(chǎn)生3個(gè)文件
從shelve中數(shù)據(jù)讀取:get方法
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:ZhengzhengLiu import shelve import datetime d = shelve.open('shelve_test') # 打開(kāi)一個(gè)文件 print(d.get("name")) print(d.get("info")) print(d.get("data"))
運(yùn)行結(jié)果:
['alex', 'rain', 'test']
{'job': 'IT', 'age': 23}
2017-09-29 18:31:12.013709
2、xml模塊
xml是實(shí)現(xiàn)不同語(yǔ)言或程序之間進(jìn)行數(shù)據(jù)交換的協(xié)議,跟json差不多,但json使用起來(lái)更簡(jiǎn)單,在json還沒(méi)誕生時(shí),
大家只能選擇用xml,至今很多傳統(tǒng)公司如金融行業(yè)的很多系統(tǒng)的接口還主要是xml。xml的格式如下,就是通過(guò)<>節(jié)點(diǎn)來(lái)區(qū)別數(shù)據(jù)結(jié)構(gòu)的。
(1)xml文件示例代碼如下:文件名為:xml_test.xml
<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data>
(2)Python中操作xml模塊
xml協(xié)議在各種語(yǔ)言里的都是支持的,在python中可以用以下模塊操作xml 。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:ZhengzhengLiu #python中操作xml模塊 import xml.etree.ElementTree as ET tree = ET.parse("xml_test.xml") #要處理的xml文件名 root = tree.getroot() #root是一個(gè)內(nèi)存對(duì)象 print(root) print(root.tag) #打印標(biāo)簽名 #print(ET.parse("xml_test.xml").getroot().tag) # 遍歷xml文檔 for child in root: print(child.tag, child.attrib) #打印下一級(jí)的標(biāo)簽名和屬性 for i in child: print(i.tag,i.attrib,i.text)
運(yùn)行結(jié)果:
<Element 'data' at 0x0062E8A0>
data
country {'name': 'Liechtenstein'}
rank {'updated': 'yes'} 2
year {} 2008
gdppc {} 141100
neighbor {'direction': 'E', 'name': 'Austria'} None
neighbor {'direction': 'W', 'name': 'Switzerland'} None
country {'name': 'Singapore'}
rank {'updated': 'yes'} 5
year {} 2011
gdppc {} 59900
neighbor {'direction': 'N', 'name': 'Malaysia'} None
country {'name': 'Panama'}
rank {'updated': 'yes'} 69
year {} 2011
gdppc {} 13600
neighbor {'direction': 'W', 'name': 'Costa Rica'} None
neighbor {'direction': 'E', 'name': 'Colombia'} None
只遍歷節(jié)點(diǎn)year,代碼如下:
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:ZhengzhengLiu #python中操作xml模塊 import xml.etree.ElementTree as ET tree = ET.parse("xml_test.xml") #要處理的xml文件名 root = tree.getroot() #root是一個(gè)內(nèi)存對(duì)象 print(root) print(root.tag) #打印標(biāo)簽名 # 只遍歷year 節(jié)點(diǎn) for node in root.iter('year'): print(node.tag, node.text)
運(yùn)行結(jié)果:
<Element 'data' at 0x0050E8D0>
data
year 2008
year 2011
year 2011
3、configparser模塊
用于生成和修改常見(jiàn)配置文檔,常見(jiàn)文檔格式如下:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
Python生成配置文檔:
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:ZhengzhengLiu #python生成配置文檔 import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile)
4、hashlib模塊
做一個(gè)映射關(guān)系,將字符串轉(zhuǎn)成數(shù)字,用于加密相關(guān)的操作。
3.x里主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:ZhengzhengLiu import hashlib m = hashlib.md5() #生成對(duì)象 m.update(b"Hello") m.update(b"It's me") print(m.digest()) m.update(b"It's been a long time since last time we ...") print(m.digest()) #2進(jìn)制格式hash print(len(m.hexdigest())) #16進(jìn)制格式hash print(m.hexdigest()) # ######## md5 ######## hash = hashlib.md5() hash.update(b'admin') print("md5:",hash.hexdigest()) # ######## sha1 ######## hash = hashlib.sha1() hash.update(b'admin') print("sha1:",hash.hexdigest()) # ######## sha256 ######## hash = hashlib.sha256() hash.update(b'admin') print("sha256:",hash.hexdigest())
運(yùn)行結(jié)果:
b']\xde\xb4{/\x92Z\xd0\xbf$\x9cR\xe3Br\x8a'
b'\xa0\xe9\x89E\x03\xcb\x9f\x1a\x14\xaa\x07?<\xae\xfa\xa5'
32
a0e9894503cb9f1a14aa073f3caefaa5
md5: 21232f297a57a5a743894a0e4a801fc3
sha1: d033e22ae348aeb5660fc2140aec35850c4da997
sha256: 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918
5、hmac 模塊
它內(nèi)部對(duì)我們創(chuàng)建 key 和 內(nèi)容 再進(jìn)行處理然后再加密。
散列消息鑒別碼,簡(jiǎn)稱(chēng)HMAC,是一種基于消息鑒別碼MAC(Message Authentication Code)的鑒別機(jī)制。
使用HMAC時(shí),消息通訊的雙方,通過(guò)驗(yàn)證消息中加入的鑒別密鑰K來(lái)鑒別消息的真?zhèn)?;一般用于網(wǎng)絡(luò)通信中消息加密。
前提是雙方先要約定好key,就像接頭暗號(hào)一樣,然后消息發(fā)送把用key把消息加密,接收方用key + 消息明文再加密,
拿加密后的值 跟 發(fā)送者的相對(duì)比是否相等,這樣就能驗(yàn)證消息的真實(shí)性,及發(fā)送者的合法性了。
import hmac h = hmac.new(b'zxc', 'cvb你好'.encode(encoding="utf-8")) print(h.digest()) print(h.hexdigest()) #運(yùn)行結(jié)果: #b'\xc1\x89\t#VQ\xa4\x00\xbf\xed\xb2_\xc1s\xfa\xd2' #c18909235651a400bfedb25fc173fad2
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python操作xml數(shù)據(jù)技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- Python?configparser模塊的用法示例代碼
- Python中Parser的超詳細(xì)用法實(shí)例
- python中parser.add_argument()用法實(shí)例(命令行選項(xiàng)、參數(shù)和子命令解析器)
- Python Parser的用法
- Python ArgumentParse的subparser用法說(shuō)明
- Python3中configparser模塊讀寫(xiě)ini文件并解析配置的用法詳解
- Python HTML解析模塊HTMLParser用法分析【爬蟲(chóng)工具】
- Python中optparser庫(kù)用法實(shí)例詳解
- python命令行參數(shù)解析OptionParser類(lèi)用法實(shí)例
- Python中Parser的用法小結(jié)
相關(guān)文章
python使用numpy計(jì)算兩個(gè)框的iou方法示例
這篇文章主要介紹了python使用numpy計(jì)算兩個(gè)框的iou方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08python UIAutomator2使用超詳細(xì)教程
這篇文章主要介紹了python UIAutomator2使用超詳細(xì)教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02Python常見(jiàn)讀寫(xiě)文件操作實(shí)例總結(jié)【文本、json、csv、pdf等】
這篇文章主要介紹了Python常見(jiàn)讀寫(xiě)文件操作,結(jié)合實(shí)例形式總結(jié)分析了Python常見(jiàn)的各種文件讀寫(xiě)操作,包括文本、json、csv、pdf等文件的讀寫(xiě)與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-04-04Python 通過(guò)requests實(shí)現(xiàn)騰訊新聞抓取爬蟲(chóng)的方法
今天小編就為大家分享一篇Python 通過(guò)requests實(shí)現(xiàn)騰訊新聞抓取爬蟲(chóng)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02matplotlib繪制多個(gè)子圖(subplot)的方法
這篇文章主要介紹了matplotlib繪制多個(gè)子圖(subplot)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12解決已經(jīng)安裝requests,卻依然提示No module named requests問(wèn)題
今天小編就為大家分享一篇解決已經(jīng)安裝requests,卻依然提示No module named 'requests'問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05詳解python模塊pychartdir安裝及導(dǎo)入問(wèn)題
這篇文章主要介紹了python模塊pychartdir導(dǎo)入問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10Anaconda下Python中h5py與netCDF4模塊下載與安裝的教程詳解
這篇文章主要為大家詳細(xì)介紹了基于Anaconda,下載并安裝Python中h5py與netCDF4這兩個(gè)模塊的方法,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01