Used to build and modify common configuration documents
import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘, # 方法一:增加一个 default setion ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘}config[‘klvchen.com‘] = {} # 方法二:增加一个 klvchen.com setionconfig[‘klvchen.com‘][‘User‘] = ‘kl‘config[‘topsecret.server.com‘] = {} # 方法三:添加一个 topsecret.server.comtopsecret = config[‘topsecret.server.com‘]topsecret[‘Host Port‘] = ‘50022‘ topsecret[‘ForwardX11‘] = ‘no‘ with open(‘example.ini‘, ‘w‘) as configfile: config.write(configfile)
Generate the Example.ini document in the current directory:
[DEFAULT]compressionlevel = 9compression = yesserveraliveinterval = 45[klvchen.com]user = kl[topsecret.server.com]host port = 50022forwardx11 = no
Common operations
import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)# 获取 DEFAULT 的键值print(config.defaults())运行结果:OrderedDict([(‘compressionlevel‘, ‘9‘), (‘compression‘, ‘yes‘), (‘serveraliveinterval‘, ‘45‘)])# 获取除 DEFAULT 外的 setionprint(config.sections()) 运行结果: [‘bitbucket.org‘, ‘topsecret.server.com‘]# 判断 setion 是否存在print(‘klvchen.com‘ in config)运行结果: Trueprint(config.has_section(‘klvchen.com‘))运行结果: True# 获取 setion 中的某个键值print(config[‘klvchen.com‘][‘User‘])运行结果: klprint(config[‘DEFAULT‘][‘compression‘])运行结果: yes# 获取所有的 setion,包括 defaultfor key in config: print(key)运行结果:DEFAULTklvchen.comtopsecret.server.com# 删除setionconfig.remove_section(‘topsecret.server.com‘) # 整个setion下的键值对都会删除config.write(open(‘example.ini‘, ‘w‘)) # 需要重新写入文件# klvchen.com setion 下修改键值,没有即添加 config.set(‘klvchen.com‘, ‘age‘, ‘28‘)config.write(open(‘example.ini‘, ‘w‘)) # 需要重新写入文件
Python Configparser Module