python 之ConfigParser
- ConfigParser 简介
ConfigParser是用来操作配置文件的模块。
说明:[**]为配置文件的section,基本格式为
[section]
key = value
eg:
[db]
db_host = 127.0.0.1
db_port = 22
db_user = root
db_pass = rootroot
[concurrent]
thread = 10
processor = 20 - eg
#-*- encoding:UTF-8 -*- import ConfigParser def main(): #初始化 cf = ConfigParser.ConfigParser() cf.read("test.conf") # 获得所有的section section = cf.sections() print 'section:', section #获取指定section下所有的option(key) keys = cf.options("db") print 'options:', keys #获取指定section的option的值 value = cf.items("db") print 'db:', value #可以按照类型读取出来,同样的还有getfloat、getboolean 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 #修改一个option(key)的值,(记得写回去) cf.set("db", "db_pass", "hanhong") 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")) if __name__ == "__main__": main()
输出:
section: ['db', 'concurrent'] options: ['db_host', 'db_port', 'db_user', 'db_pass'] db: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'rootroot')] db_host: 127.0.0.1 db_port: 22 db_user: root db_pass: rootroot thread: 10 processor: 20