Python模块学习笔记(xml,ConfigParser)

1,061 views次阅读
没有评论

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协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml

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)

修改和删除XML文档内容

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
    node.text = str(new_year)
    node.set("updated","yes")
 
tree.write("xmltest.xml")
 
 
#删除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
 
tree.write('output.xml')

创建xml文档

import xml.etree.ElementTree as ET

new_xml = ET.Element("personinfolist")

personinfo = ET.SubElement(new_xml,"personinfo",attrib={"enrolled":"yes"})
name = ET.SubElement(personinfo,"name")
age = ET.SubElement(personinfo,"age",attrib={"checked":"no"})
sex = ET.SubElement(personinfo,"sex")
name.text=  'alex'
age.text = '56'
sex.text = 'man'


personinfo2= ET.SubElement(new_xml,"personinfo2",attrib={"enrolled":"no"})
name = ET.SubElement(personinfo2,"name")
age = ET.SubElement(personinfo2,"age",attrib={"checked":"no"})
sex = ET.SubElement(personinfo2,"sex")
name.text = "wangx"
sex.text = 'man'
age.text = '19'

et = ET.ElementTree(new_xml)    #生成文档对象
et.write("test.xml",encoding="utf-8",xml_declaration=True)

ET.dump(new_xml)    #打印生成的格式
<?xml version='1.0' encoding='utf-8'?>
<personinfolist>
    <personinfo enrolled="yes">
        <name>alex</name>
        <age checked="no">56</age>
        <sex>man</sex>
    </personinfo>
    <personinfo2 enrolled="no">
        <name>wangx</name>
        <age checked="no">19</age>
        <sex>man</sex>
    </personinfo2>
</personinfolist>

ConfigParser

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

来看一个好多软件的常见文档格式如下

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

用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)

configparser增删改查语法

[section1]
k1 = v1
k2:v2
  
[section2]
k1 = v1
 
import ConfigParser
  
config = ConfigParser.ConfigParser()
config.read('i.cfg')
  
# ########## 读 ##########
secs = config.sections()
print secs
options = config.options('group2')
print options
  
item_list = config.items('group2')
print item_list
  
val = config.get('group1','key')
val = config.getint('group1','key')
  
# ########## 改写 ##########
sec = config.remove_section('group1')
config.write(open('i.cfg', "w"))
  
sec = config.has_section('wupeiqi')
sec = config.add_section('wupeiqi')
config.write(open('i.cfg', "w"))
  
  
config.set('group2','k1',11111)
config.write(open('i.cfg', "w"))
  
config.remove_option('group2','age')
config.write(open('i.cfg', "w"))

 

Honest1y
版权声明:本站原创文章,由Honest1y于2018年03月06日发表,共计5212字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)