Python语法之ConfigParser 思维导图

ConfigParser 功能代码:

import io
import sys
import configparser

sys.stdout = io.TextIOWrapper(sys.stdout.detach(),encoding='utf-8')

#实例化 ConfigParser 并加载配置文件
cp = configparser.ConfigParser()
cp.read('config.conf',encoding="utf-8")
#获取 section 列表、option 键列表和 option 键值元组列表 
print('all sections:', cp.sections())         # sections: ['db', 'ssh']
print('options of [db]:', cp.options('db'))  # options of [db]: ['host', 'port', 'user', 'pass']
print('items of [ssh]:', cp.items('ssh'))    # items of [ssh]: [('host', '192.168.10.111'), ('user', 'sean'), ('pass', 'sean')]

#取指定的配置信息
print('host of db:', cp.get('db', 'host'))     # host of db: 127.0.0.1
print('host of ssh:', cp.get('ssh', 'host'))   # host of ssh: 192.168.10.111
#按类型读取配置信息:getint、 getfloat 和 getboolean
print(type(cp.getint('db', 'port')))        # <type 'int'>
#判断 option 是否存在
print(cp.has_option('db', 'host'))    # True
#设置 option
cp.set('db', 'host','192.168.10.222')
#删除 option
cp.remove_option('db', 'host')
#判断 section 是否存在
print(cp.has_section('db'))    # True
#添加 section
cp.add_section('new_sect')
# 删除 section
cp.remove_section('db')
#保存配置,set、 remove_option、 add_section 和 remove_section 等操作并不会修改配置文件,write 方法可以将 ConfigParser 对象的配置写到文件中
cp.write(open('config.conf', 'w'))
cp.write(sys.stdout)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值