Python - ConfigParser模块读写配置文件
2016-12-29 23:16
746 查看
在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在Python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍。
Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如:
假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:
执行结果:
Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如:
[db] db_host=192.168.1.1 db_port=3306 db_user=root db_pass=password [concurrent] thread=200 processor=400
假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:
#-*- encoding: utf-8 -*- import ConfigParser,string,os,sys cf = ConfigParser.ConfigParser() cf.read("test.conf") # 返回所有的section s = cf.sections() print 'section:', s o = cf.options("db") print 'options:', o v = cf.items("db") print 'db:', v print '-'*60 #可以按照类型读取出来 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 #修改一个值,再写回去 cf.set("db", "db_pass", "zhaowei") cf.write(open("test.conf", "w")) #添加一个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")) #移除section 或者option 。(只要进行了修改就要写回的哦) cf.remove_option('liuqing','int') cf.remove_section('liuqing') cf.write(open("test.conf", "w"))
执行结果:
section: ['db', 'concurrent'] options: ['db_host', 'db_port', 'db_user', 'db_pass'] db: [('db_host', '192.168.1.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'password')] ------------------------------------------------------------ db_host: 192.168.1.1 db_port: 3306 db_user: root db_pass: password thread: 200 processor: 400
相关文章推荐
- Python自动化测试 (二) ConfigParser模块读写配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- Python自动化测试 -ConfigParser模块读写配置文件
- Python自动化测试 (二) ConfigParser模块读写配置文件
- 用ConfigParser模块读写配置文件——Python
- Python模块之ConfigParser - 读写配置文件
- Python模块之ConfigParser - 读写配置文件
- Python模块之ConfigParser - 读写配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- Python模块之ConfigParser - 读写配置文件
- $用ConfigParser模块读写conf配置文件
- Python模块之: ConfigParser 配置文件读取
- python模块之ConfigParser: 用python解析配置文件[zt]
- Python Configparser模块读取、写入配置文件
- Python模块学习之ConfigParser读写配置信息
- Python配置文件解析模块ConfigParser使用实例
- Python自动化测试 (二) ConfigParser模块读写配置文件
- [zz]python模块之ConfigParser: 用python解析配置文件
- Python之配置文件模块 ConfigParser
- python模块之ConfigParser:解析配置文件模块