600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 如何读取通用配置文件conf?

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

时间:2020-05-29 06:14:31

相关推荐

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

通用配置文件conf格式

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

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

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

[DEFAULT]conf_str = namedbn = mysqluser = roothost = localhostport = 3306[db]user = aaapw = pppdb = example[db2]host = 127.0.0.1pw = wwwdb = 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")

aaapppmysql

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

from configparser import ConfigParserdef 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']aaappplocalhost

如何写入简单举例

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

import configparserconfig = configparser.ConfigParser()config['DEFAULT'] = {'ServerAliveInterval': '45','Compression': 'yes','CompressionLevel': '9'}config[''] = {}config['']['User'] = 'hg'config[''] = {} # 定义空字典类型topsecret = config['']topsecret['Port'] = '50022'# 添加键值对topsecret['ForwardX11'] = 'no' config['DEFAULT']['ForwardX11'] = 'yes'with open('example.ini', 'w') as configfile: # 写入配置文件config.write(configfile)

结果example.ini内容如下:

[DEFAULT]serveraliveinterval = 45compression = yescompressionlevel = 9forwardx11 = yes[]user = hg[]port = 50022forwardx11 = no

参考地址:/zh-cn/3.11/library/configparser.html#

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。