Config parser --module for parsing configuration files
What is a configuration file?
Files that contain configuration program information are called configuration files
What kind of data should be used as configuration information
Information that needs to be changed but not changed for example: path to a data file
There are only two types of content in the configuration file:
One is section partitioning
One option is a key=value form
The most we've used is the get feature-used to get a configuration option from the configuration file
Examples are as follows:
# The contents of the test.cfg file are as follows: # path-dependent configuration = c://myfile/test.txt# user-related configuration = Kogan # service-related configuration = 192.168.1.2
ImportConfigparser#Create a parserConfig =Configparser. Configparser ()#Read and parse test.cfgConfig.read ("test.cfg", encoding="Utf-8")#get the information you need#Get all partitionsPrint(Config.sections ()) Get all optionsPrint(Config.options ("User") to get the value of an optionPrint(Config.get ("Path","Db_path"))Print(Type (Config.get ("User"," Age")))#get returns all string types if a conversion type is required to use the get+ corresponding type directly (bool int float)Print(Type (Config.getint ("User"," Age")))Print(Type (Config.get ("User"," Age")) Whether an option config.has_option () is not used by a partition config.has_section () to add Config.add_section ("Server") Config.set ("Server","URL","192.168.1.2") Delete config.remove_option ("User"," Age") Modify the Config.set ("Server","URL","192.168.1.2") write back to the file with open ("test.cfg","WT", encoding="Utf-8") as F:config.write (f)
Config Parser module