【Python】基础部分 -- 常用模块 -- xml / configparser .文件解析器
1. xml / configparser .文件解析器
1) xml .xml文件解析器
格式: 通过<>节点标记区别数据结构,操作基本靠遍历
import xml.etree.ElementTree as ET
查:
tree = ET.parse(xml_filename)
root = tree.getroot()
print(root.tag)
for child in root:
print(child.tag.child.attrib)
for i in child:
print(i.tag, i.text)
for node in root.iter('year'):
print(node.tag, node.text)
修改
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set('updated', 'yes')
tree.write(xml_filename)
删除
for country in root.findall('country')
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write(xml_filename)
创建
import xml.etree.ElementTree as ET
new_xml = ET.Element('namelist')
name = ET.SubElment(new_xml, 'name', arrrib={'enrolled':'yes'})
age = ET.SubElment(name, 'age', attrib={'checked':'no'} )
age.text = '33'
sex = ET.SubElment(name, 'sex')
sex.text = 'male'
name2 = ET.SubElment(new_xml, 'name', arrrib={'enrolled':'no'})
age = ET.SubElment(name2, 'age')
age.text = '19'
et = ET.ElementTree(new_xml)
et.write('test.xml', encoding='utf-8', xml_declaration=True)
ET.dump(new_xml)
2) configparser .ini文件解析器
解析配置文件 conf.ini
import configparser
conf = configparser.ConfigParser() #生成对象
conf.read('conf.ini') #读取文件
conf.write('conf.ini') #保存文件
增
conf.add_section('section') #添加节点
改
conf.set('section', 'key', 'value') #修改键值
查
local_key = conf.get(section, key) #读取指定键值
删除
conf.remove_option('section', key) #删除键值
conf.remove_section('section') #删除节点
其他
.has_section #是否有节点
.has_option #是否有键
.option(节点名) #查询节点内的所有键
conf['节点名']['键名'] =‘键值’
print(dir(conf)) #打印所有方法