如何读取通用配置文件conf?

通用配置文件conf格式

大家经常见到各种各样的配置文件格式,有json格式(JavaScript Object Notation),ini格式(Initialization File)yml(Yet Another Markup Language)标记语言等等。

真实场景中常用于MySQL数据库my.cnf配置读取,或者在项目中进行配置文件读写操作等。

本次我们关注的是conf或者ini文件格式,举例如下:

[DEFAULT]
conf_str = name
dbn = mysql
user = root
host = localhost
port = 3306

[db]
user = aaa
pw = ppp
db = example

[db2]
host = 127.0.0.1
pw = www
db = example

如何读取呢?

本次以python语言读取案例,典型读取操作

from configparser import ConfigParser # 配置文件解析器

def get_conf(path):
    """
    get conf file
    :param path:
    :return:
    """
    cf = ConfigParser()
    cf.read(path)
    db1_user =  cf.get("db", "user") # 读取db层级下的user值
    db1_pw =  cf.get("db", "pw") # 读取另一个值
    db1_db =  cf.get("DEFAULT", "dbn") # 读取Default区块下的值

    print(db1_user)
    print(db1_pw)
    print(db1_db)


if __name__ == '__main__':
    get_conf("./format.conf")
aaa
ppp
mysql

读取配置文件写法还有另一种形式。

from configparser import ConfigParser

def get_conf(path):
    """
    get conf file
    :param path:
    :return:
    """
    cf = ConfigParser()
    cf.read(path)
    print(cf.sections()) # 读取区块[信息]
    db1_user =  cf["db"]["user"]
    db1_pw =  cf["db"]["pw"]
    db1_db =  cf["DEFAULT"]["db"]

    print(db1_user)
    print(db1_pw)
    print(db1_db)


if __name__ == '__main__':
    get_conf("./format.conf")
['db', 'db2']
aaa
ppp
localhost

如何写入简单举例

至于写入实际上类似,先进行字典键值对组装,然后再写入文件结束。

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {} # 定义空字典类型
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'     # 添加键值对
topsecret['ForwardX11'] = 'no'  
config['DEFAULT']['ForwardX11'] = 'yes'

with open('example.ini', 'w') as configfile: # 写入配置文件
  config.write(configfile)

结果example.ini内容如下:

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
port = 50022
forwardx11 = no

参考地址:https://docs.python.org/zh-cn/3.11/library/configparser.html#

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

魔幻云

告诉自己是时候输出知识啦!

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

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

打赏作者

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

抵扣说明:

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

余额充值