python configparser模块

"""
from:别嫌麻烦
"""
"""
ConfigParser 配置解释器
在Python中经常用到的配置文件有.conf和.ini
配置文件以option = valuse 开头、以';'注释、section 不可重复
"""
import configparser, os

A = 'F:\pycharm\python_\databases\databases_config_dev.cfg'
conf = configparser.ConfigParser()
conf.read(A, "utf-8")  # todo:读取该路径下的指定配置文件,设置编码为utf-8
section = conf.sections()  # todo:配置文件中所有的sections 也可以理解为每个title,返回的sections以数列方式收集
# option_ = options(section)
option_ = conf.options('biexianmafan')  # todo:收集指定section的options
# print(option_)
conf.has_option('biexianmafan', 'biexianmafan_host')  # todo:判断指定section中是否有指定的option,返回值为布尔类型
conf.has_section('')  # todo:判断是否有section
item_ = conf.items('biexianmafan')  # todo:返回指定section的所有键值对
# print(item_)
get_options = conf.get('biexianmafan', 'biexianmafan_host')  # todo:获取指定section的option值,返回类型为str
# print(get_options)
# get_options_int = conf.getint('')  # todo:返回类型发生改变,变成int类型,但是也要注意option是否支持int
"""
获取指定option返回值 不止有get()、getint(),还有getboolean(),getfloat().
***但是一定要注意引用返回值的地方支持什么类型***
"""
# todo:ConfigParser()中的增删改很鸡肋,有那时间还不如直接进conf中直接操作
"""写入方法一"""
conf['balabala'] = {'balabala': '2114'}  # todo:写入新的section和options 字典格式
# with open(os.path.abspath('../databases/databases_config_dev.cfg'), 'w') as conffile:
#     conf.write(conffile)
#     # todo: 太鸡肋!打开的文件必须是原文件路径!不是原路径会在编写write的py文件路径下新建一个cfg或者ini文件!
#     # todo:不能执行同一个插入section命令否则会覆盖最后一个
"""写入方法二"""
conf['fortest'] = {}
conf['fortest']['biubiubiu'] = 'die'
"""写入方法三"""
conf['testforus'] = {}
test = conf['testforus']
test['test1'] = '2114'
test['test2'] = '1214'
with open(os.path.abspath('../../databases/databases_config_dev.cfg'), 'w') as conffile:
    conf.write(conffile)


_path = os.path.split(os.path.realpath(__file__))[0]
print(_path)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值