配置文件的目的
配置文件的优点:
1、将变量开放出去,方便修改
2、方便查看当前使用插件、数据库连接的信息
3、防止太多变量写死,改一个变量值要改很多地方
之前我们已经介绍过python读取yaml文件了
配置文件介绍
- 所用到的包——configparser ,;
- 常见的配置后缀 .conf、.ini、.cfg;
- 配置文件示例
- 在配置文件中分为section(节)、option(选项–键值对)
读取配置文件
因为配置文件本身就是一个文件,那么需要打开或读取才可以进行操作
- read(filename):直接读取配置内容
- sections():以列表形式获得所有section
- options(section):获得改section中所有的options
- items(section):以键值对的形式来获取section下的option;
- get(section,option):得到对应section下option的值;
- getint(section,option):得到对应的section中的option的值,并以int类型返回
代码示例
import os
import configparser
from realePath import realPath
class readConfigs():
"""封装配置文件读取类,随时想读随时调"""
def __init__(self):
path = os.path.join(realPath().get_Path(), 'config.ini')
# 获取当前的config配置读取器
self.parser = configparser.ConfigParser()
self.parser.read(path, encoding='utf-8')
#使用配置读取器读取配置文件中的内容
# ini文件路径,section部分,option选项参数
def get_items(self,section_name):
"""获取section对应的option键值对"""
value = self.parser.items(section_name)
#列表套元组
return value
def get_sections(self):
sections_name = self.parser.sections()
return sections_name
def get_requst(self,name):
value = self.parser.get('PARAMS',name)
return value
if __name__ == '__main__':
print(readConfigs().get_requst(name='url'))
print(readConfigs().get_items('PARAMS'))
print(readConfigs().get_sections())