ConfigParser
python 3.x 版本中改名为configparser
。
$ cat config
[Web]
project=UAir
user=root
pass=123123
[DB]
project=MySQL
user=root
pass=123123
获取配置信息
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read('config')
>>> config.options('Web')
['project', 'user', 'pass']
>>> config.items('Web')
[('project', "'UAir'"), ('user', "'root'"), ('pass', '123123')]
>>> config.get('Web', 'user')
"'root'"
>>> config.getint('Web', 'pass')
123123
修改配置信息
删除section
>>> sec = config.remove_section('Web')
>>> config.write(open('config', "w"))
新增section
>>> config.has_section('Web')
False
>>> config.add_section('Web')
>>> config.set('Web', 'name','nginx')
>>> config.set('Web', 'path','/opt/nginx')
>>> config.write(open('config', "w"))
删除option
>>> config.remove_option('DB','project')
True
>>> config.write(open('config', "w"))