Preface: at present, the vast majority of computer programs we use, whether office software, browser, or even games and videos, are configured through the menu interface system, which has almost become the default way for us to use the machine. In python, there is also such a configuration module that can configure the code.
What is a profile
The configuration file here is different from the visual menu interface we usually see. It is in the form of code, as shown in the following example:
: question: why do I need a configuration file?
: heavy_check_mark: make the code and configuration modular and configurable, and improve the reusability of the code. When will it become configurable? When a parameter is used in many places, the parameters that often change can be configured. We only need to modify it in the configuration file instead of repeatedly modifying it everywhere in the code.
Python provides a ConfigParser module, which implements a basic configuration file parser language. The structure provided by the language is similar to that in. ini files. The common configuration file format is. ini. Conf. CFG. The configuration file consists of two file objects: section and option. A configuration file can contain one or more sections, and each section can have multiple options (key = value), as shown in the above figure.
Read configuration file
Like the file file, it needs to be opened before reading. The common methods are as follows:
read(filename) sections() options(section) items(section) get(section,option) getint(section,option)
Take conf.ini in the figure above as an example to read:
from configparser import ConfigParser # Create an object for the operation configuration file (file resolution object) conf = ConfigParser() # Read configuration file conf.read("conf.ini", encoding="utf8") # Get all section s res2 = conf.sections() print("This is res2: {}\n".format(res2)) # Get the option under the corresponding section res3 = conf.options("logging") print("This is res3: {}\n".format(res3)) # Get all key value pairs under the corresponding section res4 = conf.items("logging") print("This is res4: {}\n".format(res4)) # get method: the read contents are strings res5 = conf.get("logging", "level") print("This is res5: {}".format(res5), type(res5)) # getint method: the read contents are of type int res6 = conf.getint("mysql", "port") print("\n This is res6: {}".format(res6), type(res6))
Operation results:
C:\software\python\python.exe D:/learn/test.py This is res2: ['logging', 'mysql'] This is res3: ['level', 'f_level', 's_level'] This is res4: [('level', 'DEBUG'), ('f_level', 'DEBUG'), ('s_level', 'ERROR')] This is res5: DEBUG <class 'str'> This is res6: 3306 <class 'int'> Process finished with exit code 0
In addition to reading str and int types, float and boolean are also supported. There are no more examples here.
: balloon: Tips:
- Key value pairs available = also available: are separated
- section names are case sensitive, while option is not
- If there is a blank character at the beginning and end of the key value pair, it will be removed
- Comments can also be written in the configuration file to # or; Prefix
Write configuration file
The basic writing method is as follows:
add_section(section) set( section, option, value)
from configparser import ConfigParser # Create an object for the operation configuration file (file resolution object) conf = ConfigParser() conf.add_section('test') conf.set('test', 'name', 'Amy') conf.write(open('conf.ini', "a", encoding="utf-8"))
After running, check the contents in the conf.ini file:
Encapsulation of ConfigParser
Once encapsulated, once and for all, and then directly called. The encapsulated content is on demand.
from configparser import ConfigParser class MyConf: def __init__(self, filename, encoding="utf8"): self.filename = filename self.encoding = encoding self.conf = ConfigParser() self.conf.read(filename, encoding) def get_str(self, section, option): return self.conf.get(section, option) def get_int(self, section, option): return self.conf.getint(section, option) def get_float(self, section, option): return self.conf.getfloat(section, option) def get_bool(self, section, option): def write_data(self, section, option, value): self.conf.set(section, option, value) self.conf.write(open(self.filename, "a", encoding=self.encoding)) if __name__ == '__main__': print(conf.get_str("conf.ini", "test","name")) # test
experience in software testing, interface testing, automation testing, continuous integration and interview. If you are interested, you can go to 806549072. There will be irregular sharing of test data in the group. There will also be technology giants to exchange technology with peers in the industry