Python Configparser Module

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.