# coding:utf-8
import configparser
# 初始化
cf = configparser.ConfigParser()
cf.read('testconfig.conf', encoding='utf-8')
# 获取指定section的配置信息
host = cf['db']['db_host']
port = cf['db']['db_port']
user = cf['db']['db_user']
password = cf['db']['db_pass']
print("db_host:", host)
print("db_port:", port)
print("db_user:", user)
print("db_pass:", password)
# 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中
s = cf.sections()
print('section:', s)
# 获取指定section 的options。即将配置文件某个section 内key 读取到列表中
o = cf.options('db')
print('option:', o)
# 获取指定section 的配置信息。
v = cf.items('db')
print('db:', v)
# 按照类型读取指定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)
# 设置某个option 的值。
cf.set('db', 'db_pass', 'zhang')
cf.write(open('testconfig.conf', 'w'))
# 添加一个section。
cf.add_section('test')
cf.set('test', 'int', '15')
cf.set('test', 'bool', 'true')
cf.set('test', 'float', '3.1415')
cf.write(open('testconfig.conf', 'w'))
# 移除section或option。(只要进行了修改就要写回的哦)
cf.remove_option('test', 'int')
cf.remove_section('test')
cf.write(open('testconfig.conf', 'w'))
参考:http://blog.csdn.net/windone0109/article/details/10550383