我们经常会用到ini或者yaml配置文件,下面学习下如何解析此类文件
1、解析ini文件
使用configparser模块,python自带的不需要安装
一个ini文件是由多个section组成,每个section中以key=vlaue形式存储数据;
1.1、ini文件的定义
ini 文件的写法通俗易懂,通常由**节**(Section)、**键**(key)和**值**(value)组成,就像以下形式:
[mysql] # sectionport=3306host=127.0.0.1user=rootpassword=123456[redis]port=6378host=127.0.0.1password=123456db=0
- [mysql]: 节(Section)
- host: 键(key)
- 127.0.0.1: 值(value)
import configparserimport osconfig = configparser.ConfigParser() #实例化base_path = os.path.dirname(os.path.abspath(__file__)) # 从一个路径中提取文件路径file_path = os.path.join(base_path, "test.ini") # 存放ini配置文件的路径config.read(file_path)section = config.sections()print(section)
获取配置文件中的所有section
[‘mysql’, ‘redis’]
1.1.1、读取节点下一个key对应的value值
import configparserimport osconfig = configparser.ConfigParser() #实例化base_path = os.path.dirname(os.path.abspath(__file__)) # 从一个路径中提取文件路径file_path = os.path.join(base_path, "test.ini") # 存放ini配置文件的路径config.read(file_path)# result1 = config['mysql']['host']result1 = config.get("mysql","host")
结果:
127.0.0.1
1.1.2、读取某个节点下的所有value值
import configparserimport osconfig = configparser.ConfigParser() #实例化base_path = os.path.dirname(os.path.abspath(__file__)) # 从一个路径中提取文件路径file_path = os.path.join(base_path, "test.ini") # 存放ini配置文件的路径config.read(file_path)#result1 = config.items('mysql')print(result1)print(dict(result1))
结果如下:
import configparserimport osconfig = configparser.ConfigParser() #实例化base_path = os.path.dirname(os.path.abspath(__file__)) # 从一个路径中提取文件路径file_path = os.path.join(base_path, "test.ini") # 存放ini配置文件的路径config.read(file_path)result1 = config['mysql']print(result1)print(dict(result1))

1.1.3、获取所有节下的键值对
for section in config.sections(): #获取所有节下的键值对print(dict(config[section]))

2、解析yaml文件
yaml是比较常见的一种配置文件,解析它需要安装pyyaml模块
pip install pyyaml
2.1、yaml文件定义
#config.yamlport: 3306host: 127.0.0.1username: sdfsfdfpassword: xxxxusers:- xiaohei- xiaobai- xiaolanmysql:port: 3306host: 192.168.1.123user: root
import yamlimport os#下面是解析with open("config.yaml", encoding="utf-8") as fr:result = yaml.load(fr, yaml.SafeLoader)print(result)

2.2、把字典写入yaml文件里
d = {'url': 'http://127.0.0.1:1111/login', 'method': 'get', 'headers': {'token': 'xxx'},'data': {'name': 'abc', 'password': 'xxx'}}with open("config2.yaml", 'w', encoding="utf-8") as fr:yaml.dump(d, fr)

3、读配置文件封装
class ConfigReader:def __init__(self, file):self.file = fileself.check_file()def check_file(self):if not os.path.isfile(self.file):raise Exception(f"解析{self.file}出错!请检查文件!")def get_ini_config(self, node="all"):config = configparser.ConfigParser()config.read(self.file)if node == "all":config_dict = {}for node in config.sections():config_dict[node] = dict(config[node])return config_dictif node not in config.sections():return {}return dict(config[node])def get_yaml_config(self, node="all"):with open(self.file, encoding="utf-8") as fr:result = yaml.load(fr, yaml.SafeLoader)if node == "all":return resultreturn result.get(node)if __name__ == '__main__':result = ConfigReader("config.yaml").get_yaml_config()print(result)# result = ConfigReader("test.ini").get_ini_config()# print(result)
