python之configparser模块(配置文件的使用)
在接口测试中,有些东西是固定不变的,比如url,若想更改的话就必须每个请求都更改,因此,可以放到配置文件中使用。
1、首先先创建一个配置文件,如图:

配置文件添加数据的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
在配置文件conf.ini添加数据,如
[database]
host=127.0.0.1
user=root
password=123456
encoding=utf-8
[love]
wife=sunxue
2、configParser 是用来读取配置文件的第三方模块,这个是python3自带的。
读取配置文件。读取文件要知道文件的路径
获取路径的代码:
注:path为路径
os.path.dirname(path):返回path中的文件夹部分,即目录
os.path.abspath(path):返回绝对路径
os.getcwd():获取当前文件的所在的路径
方法一:
path = os.path.dirname(os.path.abspath('.')) configpath = os.path.join(path, 'config/conf.ini') print(configpath)
方法二:
path = os.path.dirname(os.getcwd()) configpath = os.path.join(path, 'config/conf.ini') print(configpath)
使用configParser 首选需要初始化实例
path = os.path.dirname(os.path.abspath(os.getcwd())) configpath = os.path.join(path, 'config/conf.ini') #print(configpath) cfg = configparser.ConfigParser() #初始化onfigparser这个实例 cfg.read(configpath) #读取配置文件
2、configParser 常用方法
(1)获取所用的section,返回在列表中
path = os.path.dirname(os.getcwd()) configpath = os.path.join(path, 'config/conf.ini') cfg = configparser.ConfigParser() cfg.read(configpath) print(cfg.sections())

(2)获取指定section 的options。即将配置文件某个section 内key 读取到列表中:
path = os.path.dirname(os.getcwd()) configpath = os.path.join(path, 'config/conf.ini') cfg = configparser.ConfigParser() cfg.read(configpath) key=cfg.options('database') print(key)
(3) 获取指定section下指定option的值
path = os.path.dirname(os.getcwd()) configpath = os.path.join(path, 'config/conf.ini') cfg = configparser.ConfigParser() cfg.read(configpath) laopo=cfg.get('love','wife') #公式cfg.get('section','key') print(laopo)

(4)获取指定section的所用配置信息
path = os.path.dirname(os.getcwd()) configpath = os.path.join(path, 'config/conf.ini') cfg = configparser.ConfigParser() cfg.read(configpath) key=cfg.items('database') print(key)

(5)修改某个option的值,如果不存在则会出创建
path = os.path.dirname(os.getcwd()) configpath = os.path.join(path, 'config/conf.ini') cfg = configparser.ConfigParser() cfg.read(configpath) cfg.set('database','host','192.168.1.1') cfg.write(open(configpath,mode='w'))
(6)检查section或option是否存在,bool值
path = os.path.dirname(os.getcwd()) configpath = os.path.join(path, 'config/conf.ini') cfg = configparser.ConfigParser() cfg.read(configpath) section1=cfg.has_section('love') #查看love这个section是否存在 print(section1) option1=cfg.has_option('love','wife') #查看wife这个option是否存在 print(option1)

(7)写入文件
修改配置文件的都要有
cfg.write(open(configpath,mode='w'))
浙公网安备 33010602011771号