Configparser module is used to manipulate configuration files
The configuration file format is similar to the Windows INI file, and can contain one or more sections (section), and each section can contain multiple parameters (key-value pairs form: key=value) Configparser Common methods
1, Config=configparser.configparser ()
Create Configparser instance
2, config.sections () --> list
Returns the sequence 3, config.options (section)--> List of all the sections in the configuration file returns the
sequence
4, Config.get (section,option) of all keys in a project --> str
returns a section, option's key value
5, config.add_section (str)
adds a profile section (str)
6, Config.set (Section,option,val)
Sets the value of the key to option (Val)
7, config.read (filename) to
read configuration file
8, Config.write (obj_file)
Write configuration file
Comprehensive Example
#!/usr/bin/env python #-*-coding:utf-8-*-import configparser def writeconfig (filename): ' Write profile configuration file full Path name: param filename: ' config = configparser.configparser () section_name = ' section_1 ' Config.add_sectio
N (section_name) Config.set (section_name, "Key_1", "Value_1_1") Config.set (Section_name, "key_2", "value_1_2") Config.set (Section_name, "Key_3", "value_1_3") section_name = "Section_2" Config.add_section (section_name) CO Nfig.set (Section_name, "Key_1", "Value_2_1") Config.set (Section_name, "key_2", "Value_2_2") Config.set (Section_nam
E, "Key_3", "Value_2_3") config.write (open (filename, "W")) def updateconfig (filename, section, **KEYV): " Modify profile file name: param filename:section: param section: Configure key value pairs (Key=value):p Aram Keyv:: Return: "' Confi
g = Configparser.configparser () config.read (filename) for key into Keyv:config.set (section, key, Keyv[key]) Config.write (open (f)Ilename, "W") def printconfig (filename): ' Print profile information profile full path name: param filename: ' config = Configpa Rser. Configparser () config.read (filename) sections = config.sections () print "sections:", Sections for section In Sections:print ' [%s] '% section for option in Config.options (section): print "\t%s=%s"% (
option, Config.get (section, option)) if __name__ = = ' __main__ ': file_name = ' Test.ini ' Writeconfig (file_name)
Printconfig (file_name) updateconfig (file_name, ' section_2 ', key_2= ' modified ') print "Modified:" Printconfig (file_name)
Print "End"
Execution Results
Sections: [' section_1 ', ' section_2 ']
[section_1]
key_1=value_1_1
key_2=value_1_2
[section_2]
key_1=value_2_1
key_2=value_2_2
key_3=value_2_3
Modified:
sections: [' Section_ 1 ', ' section_2 ']
[section_1]
key_1=value_1_1
key_2=value_1_2
key_3=value_1_3
[section_ 2]
key_1=value_2_1
key_2= modified the
key_3=value_2_3
end
Test.ini File
[Section_1]
Key_1 = value_1_1
key_2 = value_1_2
key_3 = value_1_3
[section_2]
key_1 = value_2_1 key_2
= Modified
key_3 = Value_2_3