一、xml模块

  xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,

 但至今很多传统公司如金融行业的很多系统的接口还主要是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

# _*_coding:utf-8_*_

import xml.etree.ElementTree as ET
# xml 通过<> 节点区别数据结构 tree = ET.parse("xml test") # open 文件
root = tree.getroot() #f.seek(0)
#print(dir(root))
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文档内容

# _*_coding:utf-8_*_

import xml.etree.ElementTree as ET

tree = ET.parse("xml test")
root = tree.getroot() #f.seek(0) #修改
for node in root.iter('year'):
new_year = int(node.text) - 1
node.text = str(new_year) # 必须是字符串
node.set("revise_test","yes") #删除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("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 = ''
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '' et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True) ET.dump(new_xml) #打印生成的格式

二、configparser模块

  configparser模块用于生成和修改常见配置文档。

  常见配置文件格式如下:

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

  解析配置文件

#!/usr/bin/env python3
#-*- coding:utf-8 -*- import configparser conf = configparser.ConfigParser()
#print(conf.sections())
conf.read('conf.ini')
print(conf.sections())
print(conf.default_section) # DEFAULT
print(conf['bitbucket.org']['user']) # hg print(list(conf['bitbucket.org'].keys())) #
# ['user', 'maxusers', 'compression', 'compressionlevel', 'serveraliveinterval', 'forwardx11'] for k,v in conf['bitbucket.org'].items():
print(k,v)
'''
user hg
maxusers 100
compression yes
compressionlevel 9
serveraliveinterval 45
forwardx11 yes
'''
# default 中的参数是默认每个里面都有的 if 'user' in conf['bitbucket.org']:
print('it is right')

  增删改查语法

#!/usr/bin/env python3
#-*- coding:utf-8 -*- import configparser
conf = configparser.ConfigParser() conf.read('conf_test.ini')
print(dir(conf)) # 查
print(conf.options('group1')) # ['k1', 'k2']
print(conf['group1']['k1']) # v1
print(conf.get('group1','k1')) # v1 # 增加
conf.add_section('group3') # 添加节点
conf['group3']['name'] = 'cc'
conf['group3']['age'] = '21 ' # 必须为字符串
conf.write(open('conf_test_new.ini','w')) # 改
conf.set('group2','k1','')
conf.write(open('conf_test_new.ini','w')) # 删
conf.remove_option('group1','k2')
conf.remove_section('group2')
conf.write(open('conf_test_new.ini','w'))

  文章摘录整理自https://www.luffycity.com/python-book/di-4-zhang-python-ji-chu-2014-chang-yong-mo-kuai/configparser-mo-kuai.html

xml和configparser模块的更多相关文章

  1. 第二十一天,pickle json xml shelve configparser模块

    今日内容 1.pcikle 专用于python语言的序列化 2.json 是一种跨平台的数据格式 也属于序列化的一种方式 3.xml 可拓展标记语言 一种编写文档的语法 也支持跨平台 比较json而言 ...

  2. python之shelve、xml、configparser模块

    一.shelve模块 shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型 import shelve ...

  3. python模块基础之json,requeste,xml,configparser,logging,subprocess,shutil。

    1.json模块 json     用于[字符串]和 [python基本数据类型] 间进行转换(可用于不同语言之前转换),json.loads,将字符串转成python的基本数据类型,json.dum ...

  4. Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 一.前言 我们在<中我们描述了Python数据持久化的大体概念和基本处理方式,通过这些知识点我们已经 ...

  5. Learning-Python【20】:Python常用模块(3)—— shelve、pickle、json、xml、configparser

    什么是序列化/反序列化? 序列化就是将内存中的数据结构转换成一种中间格式存储到硬盘或者基于网络传输,反序列化就是硬盘中或者网络中传来的一种数据格式转换成内存中数据结构 为什么要有序列化/反序列化? 1 ...

  6. 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    [转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...

  7. 常用模块之 shutil,json,pickle,shelve,xml,configparser

    shutil 高级的文件.文件夹.压缩包 处理模块 shutil.copyfileobj(fsrc, fdst[, length]) 将文件内容拷贝到另一个文件中 import shutil shut ...

  8. Python hash、xml、configparser、sheve、shutil模块讲解 以及 面向对象初识

    今日内容: 1.hash模块2.xml模块3.configparser模块4.sheve 模块5.shutil模块 知识点一:hash什么是hash: hash是一种算法,该算法接受传入的的内容,经过 ...

  9. python常用模块:pickle、shelve、json、xml、configparser

    今日内容主要有: 一.pickle模块二.shelve模块三.json模块四.json练习五.xml模块 六.xml练习七.configparser模块 一.pickle模块 #pickle是一个用来 ...

随机推荐

  1. 理解 EventLoop

    链接 链接 node 浏览器 执行顺序有差异 macrotask microtask 一个线程会有 堆 栈 消息队列;  栈函数执行是用的, 堆用了存放定义的对象, 消息队列来处理异步的操作 a() ...

  2. Go语言的序列化与反序列化(gob)

    encoding/gob包实现了高效的序列化,特别是数据结构较复杂的,结构体.数组和切片都被支持. 实现代码如下://定义一个结构体type Student struct { Name string ...

  3. Go语言使用匿名结构体解析JSON数据

    手机拥有屏幕.电池.指纹识别等信息,将这些信息填充为 JSON 格式的数据.如果需要选择性地分离 JSON 中的数据则较为麻烦.Go 语言中的匿名结构体可以方便地完成这个操作. 首先给出完整的代码,然 ...

  4. (六)js常见四大排序

    今天突然想回顾一下四大排序,虽然说在实战中没有用到,但是想回顾一下四大排序的思想   var arr = [23, 34, 11, 22, 19, 18];   1.冒泡排序: 冒泡排序的思路分析: ...

  5. Python之json文件

    { "people":[ { "firstName": "Brett", "lastName":"McLaug ...

  6. iPhone图片拉伸:resizableImageWithCapInsets

    1 [[UIImage imageNamed:@"button_textured_30"] resizableImageWithCapInsets:UIEdgeInsetsMake ...

  7. 关于JS浅拷贝和深拷贝

    在 JS 中有一些基本类型像是Number.String.Boolean,而对象就是像这样的东西{ name: 'Larry', skill: 'Node.js' },对象跟基本类型最大的不同就在于他 ...

  8. 【3】SpringMVC的Controller

    1SpringMvc的Controller是线程安全的吗? (1)由于是单例,tomcat的多线程环境访问,属性必须是不可变的,如果可变,会产生脏数据,线程不安全 2Spring的事务管理 (1)ao ...

  9. HTML`CSS_网站页面不同浏览器兼容性问题解决

    目前,最为流行的浏览器共有五个:分别是ie,Edge浏览器(属于微软),火狐,谷歌(chrome)Safari和Opera五大浏览器. Trident内核:IE ,360,,猎豹,百度: Gecko内 ...

  10. RESTful处理JSON

    @RequestMapping(value = "/dblist", method = RequestMethod.GET) @ResponseBody public Map< ...