此模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
解析下面的文件格式:
[DEFAULT]ServerAliveInterval = 45 Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no
解析配置文件
import configparserconf = configparser.ConfigParser() # 实例化(生成对象)# print(conf.sections()) #调用sections方法 []conf.read('conf.ini') # 读配置文件(注意文件路径)print(conf.sections()) # 调用sections方法(默认不会读取default #['bitbucket.org', 'topsecret.server.com']print(conf.default_section) # ['bitbucket.org', 'topsecret.server.com']# print(conf['bitbucket.org']['User']) # hgfor key, value in conf['bitbucket.org'].items(): print(key, value) # 每个节点会有默认有DEFAULT的参数'''user hgserveraliveinterval 45compression yescompressionlevel 9forwardx11 yes'''if 'user' in conf['bitbucket.org']: print('True')
增删改查
# 查conf = configparser.ConfigParser()conf.read('conf2.ini')#print(conf.options('group1')) # 拿到keyprint(conf['group1']['k2']) # v2 拿到valueprint(conf.has_option('group1', 'key1')) # False# 增conf.add_section('group3')conf['group3']['name'] = 'Alex Li'conf['group3']['age'] = '22'conf.write(open('conf3.ini', 'w'))'''[group1]k1 = v1k2 = v2[group2]k1 = v1[group3]name = Alex Liage = 22'''# 删conf.remove_option('group1', 'k2')conf.remove_section('group1') # 把整个group1和里面的内容全删了conf.write(open('conf4.ini', 'w'))# 改conf['group1']['k1'] = 'haha'conf.write(open('conf2.ini', 'w'))
给Default增加值的话直接加,不用sections,用sections会报错,sections不会读取default
conf['DEFAULT']['character-set-server'] = 'utf-8'conf.write(open('co f2.ini', 'w'))