configparser模块

configparser模块

配置文件
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

import configparser
conf =configparser.ConfigParser()
conf.read('test.ini')                      #读取文件
print(conf.sections())                     #打印除默认部分外所有部分
print(list(conf['DEFAULT']))               #默认下所有键
print(conf['bitbucket.org']['user'])       #section下所有键不区分大小写
#用字典方法查看section元素
#conf.get_section('DEFAULT')
conf.has_section('group')                  #判断是否存在section
conf.add_section('group')                  #增加section
conf.set('group','k1','11122')             #增加或修改键值
conf.add_section('group1')                 
conf.set('group1','k1','23122') 
conf.set('group','k2','a3122')
conf.options('group')                      #获取所有键(默认部分的键值所有部分都会有)
conf.items('group')                        #获取所有键值对
conf.get('group','k1')                     #获取指定键的值
conf.remove_section('group1')              #删除指定section
conf.remove_option('group','k2')           #删除指定键
print(conf.sections())
print(conf.items('group'))
conf.write(open('test.ini','w'))
['bitbucket.org', 'topsecret.server.com']
['serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
hg
['bitbucket.org', 'topsecret.server.com', 'group']
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('k1', '11122')]
#新建一个配置文件

import configparser
conf = configparser.ConfigParser()
conf['DEFAULT'] = {'SeverPort':'8080',
                   'Fontsize':'15',
                   'Bgcolor':'red'
                   }

conf['thisisatest.com'] = {}
conf['thisisatest.com']['User']='bob'

conf['atestweb.server.cn'] = {}
top1 = conf['atestweb.server.cn']
top1['Host Port'] = '52051'
top1['Forward'] = 'no'

conf['DEFAULT']['Forward'] = 'yes'
with open('test1.ini','w') as conffile :
    conf.write(conffile)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值