One, for generating and modifying common configuration documents, the name of the current module is changed to Configparser in the python3.x version.
Ii. configuration and generation of files
1. Code
Import Configparser
Config = Configparser. Configparser ()
config["DEFAULT"] = {
"Wohaoshuai1": ' Wohaoshuai1 ',
"Wohaoshuai2": "Wohaoshuai2"
}
config["Wohsoshuai_1"] = {}
config["Wohsoshuai_1" ["user"] = "Wohaoshuai"
config["wohaoshuai_2"] = {}
AAA = config["Wohaoshuai_2"]
aaa["Host port"] = "50022"
config["DEFAULT" ["name"] = "Wohaoshuai3"
With open ("Example.ini", "W") as ConfigFile:
Config.write (ConfigFile)
2, the generated Example.ini are as follows
[DEFAULT] #此默认值为全局变量, the following key can be referenced in all nodes, such as: config["Wohaoshuai_1" ["name"], read the following environment will introduce
WOHAOSHUAI1 = Wohaoshuai1
WOHAOSHUAI2 = Wohaoshuai2
Name = Wohaoshuai3
[Wohsoshuai_1]
user = Wohaoshuai
[Wohaoshuai_2]
Host Port = 50022
Third, read the document
Import Configparser
Config = Configparser. Configparser ()
Config.sections () #读出来下面有几个节点, current 0
Config.read ("Example.ini")
Print (Config.sections ()) #列出下面有几个节点, does not contain the default
Print (Config.defaults ()) #获取defaults的key和value
Print ("wohaoshuai_1" in config) #判断对象中是否有 "wohaoshuai_1" node
Print (config["Wohaoshuai_1" ["Name"])
For key in config["Wohaoshuai_1"]:
Print (key)
Iv. Modification of documents
Python Configparser Module