The Configparser module takes the Configparser class For example, its operation basically divides into three kinds: 1) initializes, 2) reads the configuration, 3) writes the configuration.
1. Configparser Initialization
Using Configparser preferred to initialize the instance and read the configuration file:
CF = Configparser.configparser () cf.read ("Profile name")
2. Basic Read configuration file
-read (filename) reads INI file contents directly
-sections () gets all the sections and returns as a list
-options (section) gets all the option of the section
-items (section) gets all the key-value pairs of the section
-get (section,option) Gets the value of option in section, returned as a string type
-getint (section,option) Gets the value of option in section, returns the int type, and the corresponding Getboolean () and GetFloat () functions.
3. Basic Write Configuration file
-add_section (section) Add a new section
Config[section][option] = values add a new option and value
4. Modify the configuration file
-set (section,option,values) to modify the value of option
Reading configuration Files
1 ImportConfigparser2Config = Configparser. Configparser ()#Initialize3Config.read ('D:\\test.ini')#Read INI configuration file4 Print(Config.sections ())#Read Sectionns5 Print(Config.options ('Manual Scan Configuration'))#reading Options6 Print(Config.items ('Manual Scan Configuration'))#read the options and the corresponding values,7 Print(Config.get ('Manual Scan Configuration','UID'))#read the value of ' UID '
Write a configuration file
1 ImportConfigparser2Config =Configparser. Configparser ()3config['Info'] = {}#Create an empty section4info = config['Info']5info[' Age'] =' at' #Create an option with a value of ' 23 '6info['name'] ='Gally'7info['Hobby'] ='coding,reading'8info['Homepage'] ='Www.cnblogs.com/gally-jiang'9Config.write (Open'D:\\test.ini','W')#Save Write
Modifying a configuration file
-set (Section,option,value) modifies the value.
Config.set ('info','age',' + ') ) #修改值
-remove_section (secton) Delete section
Config.remove_section ('info'# Delete section
-remove_option (section,option) remove option
Config.remove_option ('info','age'# Remove option
Note: Once you have modified the contents of the configuration file, remember to save the file. Config.write (Open (' D:\\test.int ', ' W '))
Python non-return _configparser module