The Configparser module is used to generate and modify common configuration documents, and the name of the current module is changed to Configparser in the Python 3.x version. Look at a lot of software common document format as follows [Default]serveraliveinterval = 45Compression = Yescompressionlevel = 9forwardx11 = yes[bitbucket.org] User = Hg[topsecret.server.com]port = 50022forwardx11 = No if you want to use Python to generate a document like this, how do you do it? Import Configparserconfig = 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 PA rsertopsecret[' ForwardX11 ' = ' no ' # same hereconfig[' DEFAULT ' [' ForwardX11 '] = ' yes ' with open (' Example.ini ', ' W ') as con Figfile:config.write (configfile) can read it again after writing it. 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 syntax [SECTION1]K1 = V1K2:V2[SECTION2]K1 = V1import Configparserconfig = 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 (' 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 configparse module