我的Python成长之路---第六天---Python基础(19)---2016年2月20日(晴)
shelve模塊
shelve模塊是pickle模塊的擴展,可以通過key,value的方式訪問pickle持久化保存的數(shù)據(jù)
持久化保存:
| 12345678910111213 | import shelvesw = shelve.open('shelve_test.pkl') # 創(chuàng)建shelve對象name = ['13', '14', '145', 6] # 創(chuàng)建一個列表dist_test = {"k1":"v1", "k2":"v2"}sw['name'] = name # 將列表持久化保存sw['dist_test'] = dist_testsw.close() # 關(guān)閉文件,必須要有sr = shelve.open('shelve_test.pkl')print(sr['name']) # 讀出列表print(sr['dist_test']) # 讀出字典sr.close() |
說明:
1、其實shelve模塊其實就是pickle模塊的一個擴展,可以直接用key來讀取持久化保存的數(shù)據(jù),而不用原生pickle一樣通過持久化的順序來一個個讀取出來
2、sw['name']里的name其實就是key也就是自定義的一個名字,讀取的時候通過這個key就可以方便讀取出來
3、shelve_test.pkl并不是最終的文件名,shelve會自動生成如下三個后綴的文件
xml處理模塊
xml是實現(xiàn)不同語言或程序之間進行數(shù)據(jù)交換的協(xié)議,跟json差不多,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統(tǒng)公司如金融行業(yè)的很多系統(tǒng)的接口還主要是xml。
我們先來,通過一張圖認識一下xml文件的組成結(jié)構(gòu)
說明:
最外層的標簽我們稱之為跟標簽、也就是root,其他標簽都是子標簽,也就是child
| 12345678 | import xml.etree.ElementTree as ETtree = ET.parse('test.xml') # 讀取xml文件,并以Element對象的形式保存root = tree.getroot() # 獲取根for child in root: # 遍歷root下的子標簽????print(child.tag, child.attrib) # 打印標簽名和屬性????for i in child:????????print(i.tag, i.text, i.attrib) # 打印標簽名值和屬性 |
輸出結(jié)果:
country?{'name':?'Liechtenstein'}
rank?2?{'updated':?'yes'}
year?2008?{}
gdppc?141100?{}
neighbor?None?{'direction':?'E',?'name':?'Austria'}
neighbor?None?{'direction':?'W',?'name':?'Switzerland'}
country?{'name':?'Singapore'}
rank?5?{'updated':?'yes'}
year?2011?{}
gdppc?59900?{}
neighbor?None?{'direction':?'N',?'name':?'Malaysia'}
country?{'name':?'Panama'}
rank?69?{'updated':?'yes'}
year?2011?{}
gdppc?13600?{}
neighbor?None?{'direction':?'W',?'name':?'Costa?Rica'}
neighbor?None?{'direction':?'E',?'name':?'Colombia'}
我們也可以通過標簽名來獲取某一類標簽的內(nèi)容
| 12 | for node in root.iter('year'): # 僅遍歷標簽名為year的標簽????print(node.tag, node.text, node.attrib) |
輸出結(jié)果:
year?2008?{}
year?2011?{}
year?2011?{}
xml的常用操作
修改:
| 123456789 | import xml.etree.ElementTree as ETtree = ET.parse('test.xml') # 讀取xml文件,并以Element對象的形式保存root = tree.getroot() # 獲取根for node in root.iter('year'): # 遍歷year標簽????node.text = str(int(node.text) + 1) # 將year標簽的值+1,注意,讀出來的標簽的值都是字符串形式,注意數(shù)據(jù)類型轉(zhuǎn)換????node.set('updated', 'yes') # 更新該標簽tree.write('test_2.xml') # 將結(jié)果寫到文件,可以寫到源文件也可以寫到新的文件中 |
刪除:
| 12345678910 | import xml.etree.ElementTree as ETtree = ET.parse('test.xml') # 讀取xml文件,并以Element對象的形式保存root = tree.getroot() # 獲取根for country in root.findall('country'): # 遍歷所有country標簽???rank = int(country.find('rank').text) # 在country標簽查找名為rank的紙標簽???if rank > 50: # 判斷如果rank標簽的值大于50???????root.remove(country) # 刪除該標簽tree.write('test_3.xml') |
說明:
iter方法用于查找的最終標簽,也就是下面沒子標簽的標簽,獲取他的值和屬性的
findall方法用于查找還有子標簽的子標簽,然后和用fandall返回的對象的find方法獲取找到的標簽的子標簽
創(chuàng)建自己的xml文檔
| 1234567891011121314151617 | import xml.etree.ElementTree as ETnew_xml = ET.Element("namelist") # 新建根節(jié)點,或者說xml對象name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) # 給新xml對象創(chuàng)建子標簽age = ET.SubElement(name,"age",attrib={"checked":"no"}) # name標簽在創(chuàng)建子標簽age,attrib變量為屬性sex = ET.SubElement(name,"sex")sex.text = '33' # 給標簽賦值name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})age = ET.SubElement(name2,"age")age.text = '19'et = ET.ElementTree(new_xml) #生成文檔對象et.write("test.xml", encoding="utf-8",xml_declaration=True) # 將xml對象保存到文件xml_declaration表示xml文檔的聲明ET.dump(new_xml) #打印生成的格式 |
ConfigParser模塊
ConfigParser模塊是用來處理配置文件的包,配置文件的格式如下:中括號“[?]”內(nèi)包含的為section。section?下面為類似于key-value?的配置內(nèi)容。常見很多服務(wù)的都是類似這種格式的,比如MySQL
假設(shè)我們有這樣一個配置文件
[DEFAULT]
name?=?www.qq.com
[dbs]
username?=?root
passord?=?123.com
host?=?127.0.0.1
[server]
name?=?www.baidu.com
port?=?80
讀取配置文件
| 1234 | import configparserconfig = configparser.ConfigParser() # 創(chuàng)建configparser對象config.read('example.ini') # 讀取配置件print(config.sections()) # 獲取所有的session |
輸出結(jié)果
['dbs',?'server']
注意:
可以看到這里沒有輸出DEFAULT,因為在Python中DEFAULT session有特殊用途,相當(dāng)于所有session的默認值,也就是當(dāng)DEFAULT中定義了一個key和value,此時session中這個不存在的時候,這個key的值就是DEFAULT定義的value
例如
| 1 | print(config['dbs']['name']) |
輸出結(jié)果就是
www.qq.com
說明:
可以看到讀取配置文件后的返回的對象有點類似于字典,可以通過key的方式將配置文件中的值一一取出來,甚至可以使用in關(guān)鍵字判斷key是否存在
| 1 | print('server' in config) |
輸出結(jié)果
True
其他常用操作
讀:
| 1 | print(config.options('dbs')) # 獲取某個session下的所有option,也就是key |
輸出結(jié)果
['username',?'passord',?'host',?'name']
| 1 | print(config.items('dbs')) # 獲取某個session的鍵值列表,類似字典的items方法 |
輸出結(jié)果
[('name',?'www.qq.com'),?('username',?'root'),?('passord',?'123.com'),?('host',?'127.0.0.1')]
| 1 | print(config.get('dbs', 'host')) # 獲取某個session下的某個option的值 |
輸出結(jié)果
127.0.0.1
| 123 | port = config.getint('server', 'port') # 獲取某個session下的某個option的值,并以int的方式返回print(port)print(type(port)) |
類似的方法還有g(shù)etfloat和getboolean方法,當(dāng)然前提是配置文件中的值就是對應(yīng)的類型,否則會報錯
說明:
配置文件中yes、True、1、true等為真,也就是通過getboolean返回的是True,no、False、0、false等為假,也就是返回的是False
刪除:
| 12 | config.remove_option('dbs','host') # 刪除optionconfig.remove_section('server') # 刪除session |
來自為知筆記(Wiz)
轉(zhuǎn)載于:https://www.cnblogs.com/zhangxiaxuan/p/5222789.html
總結(jié)
以上是生活随笔為你收集整理的我的Python成长之路---第六天---Python基础(19)---2016年2月20日(晴)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Leetcode][第336题][JA
- 下一篇: Python: 模糊综合评价法