I. Introduction
What is the profile?
Profiles is to some fixed data, such as database accounts, test address, unified in a file inside management.
Common configuration file has INI format and YAML configuration file format, and today we start with using INI configuration file.
Second, create a profile
(A) in a project to create a config directory
(B) to create the following config.ini file in the config directory
(C) Enter your content in the configuration file
About INI configuration file syntax (by Baidu Encyclopedia) :
In config.ini file like this:
Third, read and write configuration files
Profile has been created that we are not the read configuration files. Let's read it.
3.1 Create a common directory
Create a common directory in the project root directory. The inside is to be put to the python modules, but now he is a normal directory, so we need to add __init__.py file to turn him into python package.
3.2 Creating readconfig module
Creating readconfig.py module in the common catalog.
Read the configuration file to achieve 3.3
#!/usr/bin/env python # coding=utf-8 ''' @File : readconfig.py @Time : 2019/09/30 14:11:32 @Author : wxhou @Version : 1.0 ''' import sys sys.path.append('.') import os import configparser root_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) HOST = 'server' HOST_NAME = 'url' class Config: def __init__(self): self.config_path = os.path.join(root_dir, 'config', 'config.ini') if not os.path.exists(self.config_path): raise FileNotFoundError("配置文件不存在") self.config = configparser.RawConfigParser() self.config.read(self.config_path, encoding='utf-8') def get_config(self, *args): """获取""" return self.config.get(*args) def set_config(self, *args): """修改""" self.config.set(*args) @property def host(self): """测试地址""" return self.get_config(HOST, HOST_NAME) @host.setter def host(self, value): self.set_config(HOST, HOST_NAME, value) with open(self.config_path, 'w', encoding='utf-8') as f: self.config.write(f) conf = Config() if __name__ == "__main__": print(conf.host) conf.host = 'http://www.baidu.com' print(conf.host)
So read and write a simple configuration file module is complete.
This is the end of this section.
Like python or are learning to automated testing automated testing of students, welcome to my QQ group learning together: 299 524 235 (automated test learning python)