pip instal configparser
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import configparser
import os
config=configparser.ConfigParser()
path_conf=os.path.split(os.path.realpath(__file__))[0]+'/database.conf'
config.read(path_conf,encoding='utf8')
# sections 段信息;print(config.sections()) #['database']
#获取 sectons 的 keys&values
print(config.items('database')) #[('dbhost', '127.0.0.1'), ('dbport', '3366'), ('dbname', 'test'), ('dbuser', 'test'), ('dbpassword', 'test'), ('dbcharset', 'utf8')]
#获取指定 section 的 ksys
print(config.options('database')) #['dbhost', 'dbport', 'dbname', 'dbuser', 'dbpassword', 'dbcharset']
# for option in config.options('database'):
# print(option)
#获取 key 的 value
print(config['database']['dbhost']) #127.0.0.1
print(config.get('database','dbhost')) #127.0.0.1
print(config.getint('database','dbport')) #数据类型是整数 3306
## 检查是否存在;print('database' in config) #True
print('databases' in config) #False
## 检查 value 值是否存在;print('3366' in config.get('database','dbport'))
print('test' in config.get('database','dbname'))
#添加
config.add_section('sections_2')
config.set('sections_1','ksey_12','value_12')
#删除
#删除 key12 值
config.remove_option('sections_1','ksey_12')
#删除 sections 值
config.remove_section('sections_2')
#删除 default 以外;config.clear()
config.write(open(path_conf,'w'))
#关于 DEFAULT 补充
## 删除 keys;
config.remove_option('DEFAULT', 'dbname')
## 添加
config.set('DEFAULT','dbname','test1')
config.write(open(path_conf,'w'))
#检查
print('test1' in config.get('DEFAULT','dbname'))