加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-14 05:37:09 所属栏目:Windows 来源:网络整理
导读:configparser模块 该模块用于配置文件的格式,与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。 创建文件 import configparserconfig = configparser.ConfigParser()config[ " DEFAULT " ] = { ‘ ServerAliveInte

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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读