ConfigParser 模块
一、ConfigParser简介
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容
[db] db_host = 127.0.0.1 db_port = 22 db_user = root db_pass = rootroot [concurrent] thread = 10 processor = 20
中括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。
二、ConfigParser 初始工作
使用ConfigParser 首选需要初始化实例,并读取配置文件:
cf = ConfigParser.ConfigParser() cf.read("配置文件名")
三、ConfigParser 常用方法
1. 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中:
s = cf.sections() print 'section:', s
将输出(以下将均以简介中配置文件为例):
section: ['db', 'concurrent']
2. 获取指定section 的options。即将配置文件某个section 内key 读取到列表中:
o = cf.options("db") print 'options:', o
将输出:
options: ['db_host', 'db_port', 'db_user', 'db_pass']
3. 获取指定section 的配置信息。
v = cf.items("db") print 'db:', v
将输出:
db: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'rootroot')]
4. 按照类型读取指定section 的option 信息。
db_host = cf.get("db", "db_host") db_port = cf.getint("db", "db_port") db_user = cf.get("db", "db_user") db_pass = cf.get("db", "db_pass") # 返回的是整型的
threads = cf.getint("concurrent", "thread") processors = cf.getint("concurrent", "processor")
print "db_host:", db_host print "db_port:", db_port print "db_user:", db_user print "db_pass:", db_pass print "thread:", threads print "processor:", processors 将输出: db_host: 127.0.0.1 db_port: 22 db_user: root db_pass: rootroot thread: 10 processor: 20
5. 设置某个option 的值。(记得最后要写回)
cf.set("db", "db_pass", "zhaowei") cf.write(open("test.conf", "w"))
6.添加一个section。(同样要写回)
cf.add_section('liuqing')
cf.set('liuqing', 'int', '15')
cf.set('liuqing', 'bool', 'true')
cf.set('liuqing', 'float', '3.1415')
cf.set('liuqing', 'baz', 'fun')
cf.set('liuqing', 'bar', 'Python')
cf.set('liuqing', 'foo', '%(bar)s is %(baz)s!')
cf.write(open("test.conf", "w"))
7. 移除section 或者option 。(只要进行了修改就要写回的哦)
cf.remove_option('liuqing','int') cf.remove_section('liuqing') cf.write(open("test.conf", "w"))
但是如果配置文件中,parameter选项中含有[],则无法用此模块进行解析。。因此当试用python作为开发语言时,配置文件的格式可以选择符合configparser模块的格式。。。
下面的配置就无法使用configparser模块. 会将含有[]的部分当作section来解析
[db] host[0]=127.0.0.1 host[1] = 192.168.1.123 db_port=3306 db_user=root db_pass=password [concurrent] thread=10 processor=20
使用configparser模块解析配置文件时,发现的问题:
参数名称的大写全部会转换为小写。
参数名称不能含有[,]
如果含有多个名字相同的section时,会以最后一个section为准。
还是发现了一个问题,如果不同的section中含有相同参数名字的参数,那个上面这个解析将无法判断出参数来自哪个section。
例如,myslq的配置文件中,client section和mysqld section中都含有socket和port这两个参数。如果用上面的代码,则无法判断哪个dict中的两个socket和port分别来自哪个section。
ElementTree 模块
用 ElementTree 在 Python 中解析 XML
原文: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python-with-elementtree/
译者: TheLover_Z
当你需要解析和处理 XML 的时候,Python 表现出了它 “batteries included” 的一面。 标准库 中大量可用的模块和工具足以应对 Python 或者是 XML 的新手。
几个月前在 Python 核心开发者之间发生了一场 有趣的讨论 ,他们讨论了 Python 下可用的 XML 处理工具的优点,还有如何将它们最好的展示给用户看。这篇文章是我本人的拙作,我打算讲讲哪些工具比较好用还有为什么它们好用,当然,这篇文章也可以当作一个如何使用的基础教程来看。
这篇文章所使用的代码基于 Python 2.7,你稍微改动一下就可以在 Pyt