Configparser Module
Used to generate and modify common configuration documents, the name of the current module is changed to Configparser in the Python 3.x version.
Common document formats are as follows
[DEFAULT] Serveraliveinterval = 45Compression = Yescompressionlevel = 9forwardx11 = yes [Bitbucket.org]user = HG [topsecret.server.c Om]port = 50022forwardx11 = no
What if you want to use Python to generate a document like this?
Import Configparser 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 ' c3/># same hereconfig[' DEFAULT ' [' ForwardX11 '] = ' yes ' with open (' Example.ini ', ' W ') as ConfigFile: config.write ( ConfigFile)
How to read a configuration file
>>> Import configparser>>> config = Configparser. Configparser () >>> config.sections () []>>> config.read (' Example.ini ') [' Example.ini ']>>> Config.sections () [' bitbucket.org ', ' topsecret.server.com ']>>> ' bitbucket.org ' in configtrue>>> ' Bytebong.com ' in configfalse>>> config[' bitbucket.org ' [' User '] ' HG ' >>> config[' DEFAULT ' [' Compression ' yes ' >>> Topsecret = config[' topsecret.server.com ']>>> topsecret[' ForwardX11 '] ' no ' >>> topsecret[' Port ' ' 50022 ' >>> for key in config[' bitbucket.org ']: print (key) ... usercompressionlevelserveraliveintervalcompressionforwardx11>>> config[' bitbucket.org ' [' ForwardX11 '] ' Yes
Configparser additions and deletions to check grammar
[SECTION1]K1 = V1k2:v2 [section2]k1 = v1 import configparser config = configparser.configparser () config.read (' I.cfg ') # ########## Read ########## #secs = config.sections () #print secs#options = config.options (' group2 ') #print Options #item_list = Config.items (' group2 ') #print item_list #val = config.get (' group1 ', ' key ') #val = Config.getint (' group1 ', ' key ') # ########## overwrite ########## #sec = config.remove_section (' group1 ') #config. Write ( Open (' I.cfg ', "w")) #sec = config.has_section (' Wupeiqi ') #sec = config.add_section (' Wupeiqi ') #config. Write (Open ( ' I.cfg ', ' W ')) #config. Set (' group2 ', ' K1 ', 11111) #config. Write (Open (' I.cfg ', ' W ')) #config. Remove_option (' Group2 ', ' age ') #config. Write (Open (' I.cfg ', "w"))
Python Configparser Module