import configparser
config = 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'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'
# 创建配置文件名,写入配置文件
with open("example.ini", "w") as configfile:
config.write(configfile)
'''
# 配置文件中的查询
config.read("example.ini")
print(config.sections()) # 读配置文件中除default中的其他块方法
print(config.defaults()) # 读配置文件中default内容的方法
print(config["bitbucket.org"]["User"]) # 读文件中具体块的具体值
# 循环打印出配置文件中的所有块
for key in config:
print(key)
# 循环打印出块里面的键,但default是特殊的块,打印其他块中的键时,default中的键也会打印出来
for key1 in config["bitbucket.org"]:
print(key1)
# 配置文件中增删改
config.remove_section("topsecret.server.com") # 删除配置文件中的块
config.remove_option("bitbucket.org", "User") # 删除块下面具体的键值对
config.write(open("example1.ini", "w"))
print(config.has_section("topsecret.server.com")) # 检查模块是否存在
print(config.has_option("bitbucket.org", "User")) # 检查配置文件中模块下的值是否存在
config.set("bitbucket.org", "User", "config") # 修改模块下键的值
config.add_section("topsecret.server.com") # 添加配置文件中的块
config.write(open("example2.ini", "w"))