通用配置文件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#

被折叠的 条评论
为什么被折叠?



