XML模块与configparser 模块
XML模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
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> xml数据
xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:
''' 遍历标签名 tag 遍历标签属性,attrib 遍历标签值,text 遍历属性为()的标签iter 修改标签属性,set 删除标签,remove 查找多个标签,findall 查找标签,find 先获得根节点 tree = ET.parse('XML文件名') root = tree.getiterator() ''' #______________________________________________________________________
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() print(root.tag) #遍历xml文档 for child in root: print(child.tag, child.attrib) for i in child: print(i.tag,i.text) #只遍历year 节点 for node in root.iter('year'): print(node.tag,node.text) #执行结果: year 2008 year 2011 year 2011 #---------------------------------------------------- import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() #修改 for node in root.iter('year'): new_year = int(node.text) + 1 #2008+1=2009 node.text = str(new_year) node.set("updated","yes") #修改通过set,加个属性yes tree.write("xmltest.xml") #执行结果: 会生成一个新的xmltest.xml文件,内容中会添加 <year updated="yes">2009</year> #年份+1,加个yes属性 #删除node for country in root.findall('country'): #通过对country进行遍历 rank = int(country.find('rank').text) #再用find找到rank if rank > 50: #再判断>50的值 root.remove(country) #再用remove删除 tree.write('output.xml') #写到一个新文件中
自己创建xml文档:
import xml.etree.ElementTree as ET #as后面的ET是前面的类的别名,名称随便取 new_xml = ET.Element("namelist") name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) age = ET.SubElement(name,"age",attrib={"checked":"no"}) 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) (记住重点) ET.dump(new_xml) #打印生成的格式 创建xml文档
执行结果:
会生成一个test.xml的文件,文件内容如下:
<?xml version='1.0' encoding='utf-8'?> <namelist> <name enrolled="yes"> <age checked="no" /> <sex>33</sex> </name> <name enrolled="no"> <age>19</age> </name> </namelist>
configparser 模块
configparser 模块作用: 用来读写配置文件。
一、常见文档格式如下:
1、先新建一个名字为confile文件,写入下面内容:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
示例1: 写入一个文件
import configparser config = configparser.ConfigParser() #config={} config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} with open('example1.ini', 'w') as f: config.write(f)
执行结果:
1 #会生成example1.ini文件,内容如下: 2 [DEFAULT] 3 compressionlevel = 9 4 compression = yes 5 serveraliveinterval = 45
示例2: 生成多个键值对
import configparser config = configparser.ConfigParser() #config={} 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 with open('example1.ini', 'w') as f: config.write(f)
执行结果:
#会生成example1.ini文件,内容如下: [DEFAULT] compression = yes compressionlevel = 9 serveraliveinterval = 45 [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
#-----------------------------------查询功能-------------------------------#
示例3: 实现查询功能
#查出键中user对应的值
import configparser config = configparser.ConfigParser() config.read('example1.ini') #先把文件读进来 print(config['bitbucket.org']['User']) #取出user的值 print(config['DEFAULT']['Compression']) #Compression的值 print(config['topsecret.server.com']['ForwardX11']) #ForwardX11的值
执行结果:
1 hg 2 yes 3 no
示例4:取的是bitbucket.org键的值,他会把DEFAULT的一起打印出来
DEFAULT的特殊功能:因为只要带DEFAULT键值对的,他就会把DEFAULT的键打印出来
import configparser config = configparser.ConfigParser() config.read('example1.ini') for key in config['bitbucket.org']: #取的是bitbucket.org的值,他会把DEFAULT的一起打印出来 print(key)
执行结果:
1 user 2 compression 3 compressionlevel 4 serveraliveinterval
示例5:
取的是bitbucket.org键的值,以列表的方式打印出来
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') 5 print(config.options('bitbucket.org'))
执行结果:
1 ['user', 'compression', 'compressionlevel', 'serveraliveinterval']
示例6:
取的是bitbucket.org键和值,以元组的方式打印出来
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') 5 print(config.items('bitbucket.org'))
执行结果:
1 [('compression', 'yes'), ('compressionlevel', '9'), ('serveraliveinterval', '45'), ('user', 'hg')]
示例7:
连续取值,取出compression的值
import configparser config = configparser.ConfigParser() config.read('example1.ini') print(config.get('bitbucket.org','compression')) #取出compression的值
执行结果:
1 yes #=====>取出的compression的值 yes
#-------------------------------------增加功能----------------------------------#
实现:在example1.txt文件中读取原来块的内容,增加一个新的块
1、首先必须有一个example1.txt文件,里面内容为:
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
2、增加一个块和键值对
import configparser config = configparser.ConfigParser() config.read('example1.ini') #从这里面拿到三个对象 config.add_section('yuan') #再新增加一个块 config.set('yuan','k1','11111') #给键添加键值对 config.write(open('1.cfg', "w")) #创建一个新文件
执行结果:
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no [yuan] #这就是新增加的块 k1 = 11111
#-------------------------------------删除功能----------------------------------#
示例1:
删除
import configparser config = configparser.ConfigParser() config.read('example1.ini') #从这里面拿到三个对象 config.remove_section('topsecret.server.com') #删除块和键值对的值 config.remove_option('bitbucket.org','user') config.write(open('1.cfg', "w")) #创建一个新文件
执行结果:
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 [bitbucket.org]

浙公网安备 33010602011771号