python的configparser使用实例

1 生成配置文件

conf = configparser.ConfigParser()
conf["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }

conf['bitbucket.org'] = {'User':'hg'}
conf['topsecret.server.com'] = {
    'Host Port':'50022',
    'ForwardX11':'no'
}
with open('example.ini', 'w') as configfile:
    conf.write(configfile)

2 读取或修改配置文件

2.1 查找

# 查找
import configparser
conf = configparser.ConfigParser()
# 基于字典的形式,查找文件内容
# 读取section
print(conf.sections())  # [] 读取前为空
conf.read('example.ini')
# print(conf.sections())  # ['bitbucket.org', 'topsecret.server.com']

# 查找section,基于字典形式判断
print('bytebong.com' in conf)  # False
print('bitbucket.org' in conf)  # True

# 取值 section中选项的值:
print(conf['bitbucket.org']["user"])  # hg
print(conf['DEFAULT']['Compression'])  # yes
print(conf['topsecret.server.com']['ForwardX11'])  # no
print(conf['bitbucket.org'])  # <Section: bitbucket.org>
# 取键方式1:遍历
for key in conf['bitbucket.org']:  # 注意,有default会默认default的键
    print(key)
# 取键方式2:
print(conf.options('bitbucket.org')) #取出section下所有的键,返回列表
print(conf.items('bitbucket.org'))  # 取出setciont下所有的键值对,返回元组列表。
print(conf.get('bitbucket.org', 'compression'))  # get方法:取出Section下的key对应的value

2.2 增删改

# 增删改
import configparser
config = configparser.ConfigParser()
config.read('example.ini') # 读取文件
# section增删操作
config.add_section('yuan') #
config.remove_section('bitbucket.org') #删除section

# section中选项的增删改
# 增
config.set('yuan', 'k4', '323') #set之前,必须要有section,没有就要先增加add_section,否则会报错
# 删
config.remove_option('topsecret.server.com', "forwardx11")
# 改
config.set('topsecret.server.com', 'host port', '2223')
# 写入
config.write(open('new2.ini', "w")) #写入文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值