Python的configparser生成配置文件,以及相关操作

Python中使用configparser生成配置文件,如下

import configparser

config = configparser.ConfigParser()

config["DEFAULT"] = {'ServerAliveInterval':30,
                     'Compression':'no',
                     'CompressionLevel':'7'}
config['bitbucket.org']={}
config['bitbucket.org']['User'] = 'ljj'
config['www.server.com']={}
config['baseInfo'] = {
    'BaseUrl':'test.baidu.com',
    'Port':8080
}
topsecret = config['www.server.com']
topsecret['Host Port'] = '8088'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'

with open('example.ini','w') as configfile:
    config.write(configfile)

config.read('example.ini')
print(config.sections())#读取配置文件
print(config.defaults())#读取默认的default
print(config['www.server.com']['host port'])
# 循环取出key,包括default的key值
for key in config['bitbucket.org']:
    print(key)
config.remove_section('www.server.com')
config.write(open('example.ini','w'))
print(config.has_section('www.server.com'))
config.set('bitbucket.org','user','ls')#设置键下面的键值对
config.write(open('example.ini','w'))
config.remove_option('bitbucket.org','user')#删除键下面的
config.write(open('example.ini','w'))

生成之后,生成文件example.ini

每一次的操作都是对文件的重新写入生成

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

软件测试老痞

你的支持,是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值