First, Introduction
Used to generate and modify common configuration documents, the name of the current module is changed to Configparser in the Python 3.x version.
Second, the configuration file format
[DEFAULT] Serveraliveinterval = 45Compression = Yescompressionlevel = 9forwardx11 = yes [Bitbucket.org]user = HG [topsecret.server.c Om]port = 50022forwardx11 = no
Iii. Creating a configuration file
Import configparser# generates a processing object, config = Configparser. Configparser () #默认配置 config["DEFAULT"] = {' Serveraliveinterval ': ' A ', ' Compression ': ' Yes ', ' CompressionLevel ': ' 9 '} #生成其他的配置组config [' bitbucket.org '] = {}config[' bitbucket.org ' [' User '] = ' HG ' config[' Topsecret.server.com '] = {}topsecret = config[' topsecret.server.com ']topsecret[' Host Port ' = ' 50022 ' # mutates the parsertopsecret[' ForwardX11 ' = ' no ' # same hereconfig[' DEFAULT ' [' ForwardX11 '] = ' yes ' #写入配置文件with open (' Example.ini ', ' W ') as ConfigFile: config.write (ConfigFile)
Iv. reading the configuration file
1. Read the node information
Import Configparserconfig = Configparser. Configparser () config.read (' Example.ini ') # reads the default configuration node information print (Config.defaults ()) #读取其他节点print (Config.sections ()) # Output ordereddict (' compression ', ' yes '), (' Serveraliveinterval ', ' a '), (' CompressionLevel ', ' 9 '), (' forwardx11 ', ' yes ') )]) [' bitbucket.org ', ' topsecret.server.com ']
2, the interpretation of the configuration node name exists
Print (' ssss ' in config) print (' bitbucket.org ' in config) #输出FalseTrue
3. Read the information in the configuration node
Print (config[' bitbucket.org ' [' User ']) #输出hg
4. Iterate through the configuration node all information
For key in config[' bitbucket.org ': print (Key, ': ', config[' bitbucket.org '][key]) #输出user: hgcompression: Yesserveraliveinterval:45compressionlevel:9forwardx11:yes