首页 > 其他 > 详细

常用模块-configparser模块-配置文件格式

时间:2019-07-30 12:53:18      阅读:78      评论:0      收藏:0      [点我收藏+]

configparser模块

该模块用于配置文件的格式,与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

创建文件

import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {ServerAliveInterval: 45,
                      Compression: yes,
                     CompressionLevel: 9,
                     ForwardX11:yes
                     }
config[bitbucket.org] = {User:hg}
config[topsecret.server.com] = {Host Port:50022,
                    ‘ForwardX11:no} with open(example.ini, w) as configfile:    config.write(configfile)

查找文件

import configparser
config = configparser.ConfigParser()
config.read(example.ini)
#查找文件内容,基于字典的形式,先读取才能查看

print(config.sections()) #[‘bitbucket.org‘, ‘topsecret.server.com‘]#不会显示default节里面的配置内容                
print(bytebong.com in config) # False 
print(bitbucket.org in config) # True

print(config[bitbucket.org]["user"]) # hg 查看section中对应键的值
print(config[topsecret.server.com][ForwardX11]) #no
print(config[bitbucket.org]) #<Section: bitbucket.org>

for key in config[bitbucket.org]: # 对节做循环,输出对应节中的键,如果有default节,则default节中的键也会输出
print(key)
print(config.options(bitbucket.org)) #同for循环一样,找到‘bitbucket.org‘节下所有键,包括default节中的键
print(config.items(bitbucket.org)) #找到‘bitbucket.org‘节下所有键值对
print(config.get(bitbucket.org,compression)) # yes get方法获取Section下的key对应的valu

 增删改操

import configparser
config = configparser.ConfigParser()
config.read(‘example.ini‘)
config.add_section(kinds)#增加新section 节 ‘kinds’
config.set(kinds,fruit,apple)#在节中添加键值对
config.set(bitbucket.org,user,hello)#修改键值
config.remove_section(bitbucket.org)#删除节
config.remove_option(topsecret.server.com,"forwardx11")#删除节下对应的键
config.write(open(new_config,w))#新建文件并存储

说明:配置文件时,对节的增删改查都需先read()

 

常用模块-configparser模块-配置文件格式

原文:https://www.cnblogs.com/account/p/11267088.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!