python基础--xml和configparse模块

1)XML模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多。

下面是xml的遍历查询删除修改和生成

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'

import xml.etree.ElementTree as ET

etree=ET.parse("xml.xml")
root=etree.getroot()

#遍历XML
for child in root:
    print(child.tag,child.attrib,child.text)
    for i in child:
        print("\t",i.tag,i.attrib,i.text)

#查询
for child in root.iter("year"):
    print(child.tag,child.text)

#修改和删除xml文档内容
for country in root.findall("country"):
    rank=country.find("rank").text
    if int(rank)>50:
        root.remove(country)

etree.write("xml1.xml")

for year in root.iter("year"):
    year_tmp=int(year.text)+1
    year.text=str(year_tmp)
    year.set("update","yes")
etree.write("xml2.xml")

#创建XML文件

new_xml=ET.Element("root") #生成根
name=ET.SubElement(new_xml,"name",attrib={"errol":"2013"})
age=ET.SubElement(name,"age")
age.text=str(23)

sex=ET.SubElement(name,"sex")
sex.text="boy"

et=ET.ElementTree(new_xml)
et.write("xml3.xml",encoding="utf-8",xml_declaration=True)#写入文件

ET.dump(new_xml) #打印到终端

 

2)configparse

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

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'

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'

with open('example.ini','w') as f:
    config.write(f)

config1=configparser.ConfigParser()
config1.sections()
config1.read('config.ini')
print(config1.sections())
print(config1['DEFAULT']['Compression'])

print(config1.options('bitbucket.org'))
print(config1.items('bitbucket.org'))
config1.remove_section('bitbucket.org')
config.write(open('example1.ini','w'))

 

posted on 2017-05-14 11:45  shisanjun  阅读(166)  评论(0)    收藏  举报

导航