Configparser Basic Use
Reading configuration Files
-read (filename) directly read the contents of the file
-sections () Gets all of the section and returns in the form of a list
-options (section) gets all option for this section
-items (section) gets all the key values of the section
-get (section,option) Gets the value of option in section, returned as String type
-getint (section,option) Gets the value of option in the section, returns to the int type, and the corresponding Getboolean () and GetFloat () functions.
Write configuration file
-add_section (section) Add a new section
-set (section, option, value) sets the option in sections to call write to write content to the configuration file.
A configuration file can contain one or more sections (section), and each section can have multiple parameters (key = value).
Configuration file example.conf
[db]
Db_host = 1.1.1.1
Db_port = 3306
Db_user = MySQL
Db_pass = Sasa
[Args]
AA = 1
BB = 2
[Domain]
URL = http://www.linuxyan.com
The above configuration file is either an equal sign or a colon.
Read the configuration file with Configparser example.py
#!/usr/bin/python
Import Configparser
Config = Configparser.configparser ()
Config.read (' example.conf ')
Read all nodes
s = config.sections ()
Print "All sections:", S
#结果
All sections: [' db ', ' args ', ' domain ']
Read all key for DB node
o = config.options ("db")
print ' DB options: ', O
#结果
DB options: [' db_host ', ' db_port ', ' db_user ', ' Db_pass ']
Read the specified value
Db_host = Config.get ("db", "Db_host")
Print Db_host
#结果
1.1.1.1
Reads the value of the specified type (now has get () Getint () getfloat () Getboolean ())
Db_port = Config.getint ("DB", "Port")
Print Db_port
#结果
3306
Write configuration file with Configparser example.py
#!/usr/bin/python
Import Configparser
Config = Configparser.configparser ()
Config.read (' example.conf ')
#添加一个sections
Config.add_section ("Node")
#在node中添加一个node_key = value
Config.set ("Node", "Node_key", "value")
Config.write (Open ("example.conf", "w"))
#结果
[Node]
Node_key = value