标签:blog 使用 文件 io 2014 for re c
最近发现很多接口配置都硬编码在souce file中了,于是就看了下python怎么解析配置文件,重构下这一块。
这个应该是早就要作的。。。
配置文件:
[mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid skip-external-locking old_passwords = 1 skip-bdb skip-innodb users = aa,bb,cc [names] n1 = lzz n2 = orangle n3 = zero
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#python2.7x
#config_parser.py @2014-07-25
#author: orangleliu
'''
使用 ConfigParser 模块来解析和写入配置文件,主要支持的文件类型有键值对风格的配置和json格式的配置
简单的配置应该可以应付的了
'''
import ConfigParser
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read('conf.cfg')
#str
print config.get('mysqld', 'user')
#int
print config.getint('mysqld', 'old_passwords')
#list 一种解析方法
users = config.get('mysqld', 'users')
for i in users.strip().split(','):
print i
#list 另外一种解析方法,放到section里面
names = config.items("names")
for key, name in names:
print key, name
print config.sections()
print config.has_section('default')
[Python]ConfigParser解析配置文件,布布扣,bubuko.com
标签:blog 使用 文件 io 2014 for re c
原文地址:http://blog.csdn.net/orangleliu/article/details/38117757