我们在编写脚本的过程中,可能涉及一些敏感信息,例如:用户信息、数据库信息、测试数据等,如果这些数据暴露在脚本中,无疑是不安全的。
将这些信息封装到配置文件,不仅测试时修改方便快捷,不用在脚本中检索要修改的数据,同时也从某种程度上保障了数据的安全。
下面我们介绍一种Python种常用的配置文件封装方法,使用Python自带的configparser模块来完成配置文件的信息读取。下面我们就来详细介绍它的用法。
一、配置文件格式
在使用之前,我们先来了解一下,配置文件.ini的格式。
.ini文件由节(section)、键(option)、值(value)三部分组成,其中item表示键值对。
节:[section];参数(items):键(option)=值(value);注解-使用分号;表示。
在配置文件中,所有的item(键值对),都以section为单位组合。可以理解为一个section就是若干组item。一般来说,一个[section]声明开始到下一个[section]之前,都为该section中的item,特殊情况时也可以使用section嵌套。
示例如下:
;comments of configparaser testing
[section1]
option1_1 = value1_1
option1_2 = value1_2
[section2]
option2_1 = 123456
二、configparser模块
python使用自带的configparser模块用来读取配置文件,配置文件的形式类似windows中的ini文件,pip直接安装,然后就可以import来使用了。
安装configparser:
pip install configparser
安装完成:
三、读取配置文件
1、关于配置文件路径
绝对路径:从硬盘根目录为起点到当前所在目录;
相对路径:从某个目录为起点到当前所在目录。
我们都知道,如果使用绝对路径,那么代码放在自己的电脑中,一切正常,当放在其他电脑的任意路径位置时,文件的读取就会出现异常。因此,如果我们使用相对路径,就会比较灵活。我们一般使用“…/”来表示上一级目录,“…/…/”表示上上级的目录,以此类推。
例如:
我们看file.py文件的路径:
绝对路径:D:\Folder\file.py
相对路径:.\Folder\file.py
2、实例
工程目录结构如下:
config.ini:
;comments of configparaser testing
[section1]
option1_1 = value1_1
option1_2 = value1_2
[section2]
option2_1 = 123456
代码:
import configparser
import os
# 创建实例
cf = configparser.ConfigParser()
# # 使用绝对路径,不需要os
# config_abs_path = "D:\PycharmProjects\config\config.ini"
# 获取config.ini所在目录的上一级目录,根据工程结构,也就是当前路径的上一级路径,这个根据自己的工程目录结构来获取
root_path = os.path.dirname(os.path.abspath('..'))
# 使用相对路径,拼接获得
config_path = os.path.join(root_path + '\config\config.ini')
print('----------配置文件路径:' + config_path)
# 读取配置文件
cf.read(config_path)
# 获取配置文件中所有sections
sections = cf.sections()
print('1--配置文件中所有sections:')
print(sections)
# 获取section1中所有键值对
items = cf.items('section1')
print('2--section1中所有键值对:')
print(items)
# 获取section1中所有键
options = cf.options('section1')
print('3--section1中所有键:')
print(options)
# 获取section1中option1_1的值,str
value1_1 = cf.get('section1', 'option1_1')
print('4--section1中option1_1的值,str:')
print(type(value1_1))
print(value1_1)
# 获取section2中option1_1的值,int
value2_1 = cf.getint('section2', 'option2_1')
print('5--section2中option1_1的值,int:')
print(type(value2_1))
print(value2_1)
控制台输出结果:
----------配置文件路径:D:\PycharmProjects\config\config.ini
1--配置文件中所有sections:
['section1', 'section2']
2--section1中所有键值对:
[('option1_1', 'value1_1'), ('option1_2', 'value1_2')]
3--section1中所有键:
['option1_1', 'option1_2']
4--section1中option1_1的值,str:
<class 'str'>
value1_1
5--section2中option1_1的值,int:
<class 'int'>
123456