Common Module -configparser module - Configuration File Format

configparser module

The format module configuration file, windows ini files and the like, may comprise one or more sections (sectionTop), each node can have a plurality of parameters (key = value).

Create a file

import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }
config['bitbucket.org'] = {'User':'hg'}
config['topsecret.server.com'] = {'Host Port':'50022',
                    'ForwardX11':'no'} with open('example.ini', 'w') as configfile:    config.write(configfile)

Find Files

Import ConfigParser 
config = configparser.ConfigParser ()
 config.read ( ' example.ini ' )
# Find file contents, based on the form of a dictionary, read first in order to see

Print (config.sections ()) # [ 'bitbucket.org', 'topsecret.server.com'] # is not displayed default configuration content inside section                
print ( ' bytebong.com '  in config) # False  
print ( ' bitbucket.org ' in config) # True

print (config [ ' bitbucket.org ' ] [ " User " ]) # Hg section view corresponding to the value of key in
print (config [ ' topsecret.server.com ' ] [ ' the ForwardX11 ' ]) # NO
Print (config [ ' bitbucket.org ' ]) #<Section: bitbucket.org>

for Key in config [ ' bitbucket.org ' ]: # of cycles do section, the output section corresponding to the key, if default section, the default key is also output section
Print (Key)
Print (config.options ( ' bitbucket.org ' )) # same as for loop to find all the keys 'bitbucket.org' section, including default key section
Print (config.items ( ' bitbucket.org ' )) # find all the key under 'bitbucket.org' section of the
Print (config.get ( ' bitbucket.org ' , ' compression ' )) # yes get acquired key method corresponding to at Section valu

 CRUD operations

ConfigParser Import 
config = configparser.ConfigParser () 
config.read ( 'example.ini' ) 
config.add_section ( ' kinds ' ) # add a new section section 'kinds' 
config.set ( ' kinds ' , ' Fruit ' , ' Apple ' ) # add the key section of 
config.set ( ' bitbucket.org ' , ' User ' , ' Hello ' ) # modify key 
config.remove_section ( ' the bitbucket.org ') # Delete Section 
config.remove_option ( ' topsecret.server.com ' , " ForwardX11 " ) # corresponding to the section delete key 
config.write (Open ( ' NEW_CONFIG ' , ' W ' )) # new file and store 

instructions: Configuration when the file of CRUD section are required to first read ()

 

Guess you like

Origin www.cnblogs.com/account/p/11267088.html