configparser模块 --读取配置文件
说明:
configparser模块是用来解析ini配置文件的解析器,可以包含一个或多个节,每个节可以有多个参数(键=值)。
创建配置文件:
import configparser #配置文件
config = configparser.ConfigParser()
"""生成configparser配置文件 ,字典的形式"""
"""第一种写法"""
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
"""第二种写法"""
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
"""第三种写法"""
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
"""写入后缀为.ini的文件"""
with open('example.ini', 'w') as configfile:
config.write(configfile)
读取配置文件:
# [DEFAULT]为默认节点,后面的section都可以使用它的键值
import configparser # 配置文件
config = configparser.ConfigParser()
config.read("example.ini")
## 获取所有节点
print(config.sections()) ## ['bitbucket.org', 'topsecret.server.com']
# 获取默认节点的键值
print(
config.defaults()) ## OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
## 获取默认节点的键
for item in config["DEFAULT"]:
print(item)
## 获取bitbucket.org的键,包含默认节点
print(config.options(
"bitbucket.org")) ## ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
## 输出元组,包括option的key和value
print(config.items(
'bitbucket.org')) ##[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
## 获取bitbucket.org下user的值
print(config["bitbucket.org"]["user"]) ## hg
print(config.get("bitbucket.org", "user")) ## hg
## 判断bitbucket.org节点是否存在
print('bitbucket.org' in config) ## True
## 获取option值为数字的整数
print(config.getint("topsecret.server.com", "host port")) ## 50022
删除配置文件section和option的实例(默认分组有参数时无法删除,但可以先删除下面的option,再删分组):
import configparser #配置文件
config = configparser.ConfigParser()
config.read("example.ini")
"""删除分组"""
config.remove_section("bitbucket.org")
config.write(open('example.ini', "w"))
"""删除某组下面的某个值"""
config.remove_option("topsecret.server.com","host port")
config.write(open('example.ini', "w"))