1. 程式人生 > >Python3 從零單排10_xml&configparser

Python3 從零單排10_xml&configparser

  xml模組:

  xml是實現不同語言或程式之間進行資料交換的協議,跟json差不多,但json使用起來更簡單,不過,在json還沒誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統公司如金融行業的很多系統的介面還主要是xml。

  xml的格式如下,就是通過<>節點來區別資料結構的:

<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year attr_test="yes" attr_test2
="yes">2012</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year
attr_test="yes" attr_test2="yes">2015</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year attr_test="yes" attr_test2="yes">
2015</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data>

  xml協議在各個語言裡的都 是支援的,在python中可以用以下模組操作xml

import xml.etree.ElementTree as ET

tree = ET.parse("test.xml") #類似檔案的開啟open
root = tree.getroot() #f.seek(0)
print(dir(root))  #檢視根的方法 append,clear,extend,find,findall,findtext,get,getchildren,getiterator,insert,items,iter,iterfind,itertext,keys,makeelement,remove,set
print(root.tag)  #拿到根標籤

# 遍歷xml文件
for child in root:
    print("--------",child.tag,child.attrib)
    for i in child:
        print(i.tag,i.attrib,i.text)

# 只遍歷year節點
for node in root.iter("year"):
    print(node.tag,node.attrib,node.text)

#增刪改查
#把每年+1
for node in root.iter("year"):
    new_year = int(node.text)+1
    node.text = str(new_year)
    node.set("attr_test2","yes")
tree.write("test.xml")

#刪除node
for country in tree.findall("country"):
    rank = int(country.find("rank").text)
    if rank > 50:
        root.remove(country)
tree.write("out_put.xml")

#建立xml文件
root = ET.Element("namelist")
name = ET.SubElement(root,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text="female"

name2 = ET.SubElement(root,"name",attrib={"enrolled":"no"})
age2 = ET.SubElement(name2,"age",attrib={"checked":"no"})
age2.text = "18"

et = ET.ElementTree(root)
et.write("test2.xml",encoding = "utf-8",xml_declaration=True)  #xml_declaration=True xml版本說明

ET.dump(root)

  configparser模組

  本來字典夠用,但很多如那件都會以config這種形式儲存配置檔案,所以python裡內建了這個模組,本質和字典一樣,巢狀字典

  config.ini配置檔案如下

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

  操作:

import configparser


conf = configparser.ConfigParser()  #例項化一個config檔案解析的物件
conf.read("conf.ini")  #讀取配置檔案為一個字典物件
print(dir(conf))  #可以看到很多和字典類似
print(dir(conf["bitbucket.org"])) #可以看到很多和字典類似

#
print(conf.sections())  #不會列印default
print(conf.default_section)
print(conf["bitbucket.org"]["User"]) #獲取配置項的值
for k in conf["bitbucket.org"]: #列印包含default的所有key,default預設所有節點都有該項配置,所以在迴圈其中一個節點,會列印default
    print(k)
for k,v in conf["bitbucket.org"].items():  #列印包含default的所有key/value
    print(k,v)
print(conf.has_section("asd"))  #判斷是否存在該節點
print(conf.has_section("bitbucket.org"))
print(conf.has_option("bitbucket.org","asdfg"))  #判斷該節點是否存在該key
print(conf.has_option("bitbucket.org","User"))

#增刪改  任何一個操作都要重新寫檔案才會生效
conf.read("test.ini")
print(conf.options("group1"))
print(conf["group1"]["k1"])

conf["group2"]["k1"] = "54321"
conf.set("group1","k1","123456")
conf.write(open("test1.ini","w"))  #寫入檔案才會生效

conf.remove_section("group2")  #刪除節點,不指定group2的話,會刪除所有section
conf.remove_option("group1","k1")  #刪除節點下的項,必須指定項,不然報錯
conf.write(open("test.ini","w"))  #可以直接以之前的檔案命名,內容會覆蓋