python configparser module (profile)

python configparser module

Requires the use of a configuration file, the file has

[userinfo]

username = name
password = pwd

 

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 f:
   config.write(f)

 

Import ConfigParser 

config = configparser.ConfigParser ()
 # --------------------------- find the content of the document, based on the form of a dictionary 
# Print (config. Sections ()) # [] 

config.read ( ' example.ini ' )
 Print (config.sections ())         #    [ 'bitbucket.org', 'topsecret.server.com'] 

Print ( ' bytebong.com '  in config ) # False 
Print ( ' bitbucket.org '  in config) # True 

Print (config [ 'bitbucket.org']["user"])  # hg
print(config['DEFAULT']['Compression']) #yes
print(config['topsecret.server.com']['ForwardX11'])  #no

print(config['bitbucket.org'])          #<Section: bitbucket.org>

for key in config['bitbucket.org']:      # Note that there are default default default keys 
    Print (Key) 

Print (config.options ( ' bitbucket.org ' ))   # with a for loop, find 'bitbucket.org' all key 

Print (config.items ( ' bitbucket.org ' ))     # find' 'all key-value pairs bitbucket.org 

Print (config.get ( ' bitbucket.org ' , ' compression ' )) # Key in the method of Section yes get the corresponding value

 

Import ConfigParser 
config = configparser.ConfigParser () 
config.read ( ' example.ini ' )    # read the file 
config.add_section ( ' Yuan ' )    # increased Section 
config.remove_section ( ' bitbucket.org ' )    # delete a Section 
config.remove_option ( ' topsecret.server.com ' , " ForwardX11 " )   # delete a configuration item 
config.set ( ' topsecret.server.com ' , 'k1','11111')
config.set('yuan','k2','22222')
f = open('new2.ini', "w")
config.write(f) # 写进文件
f.close()

 

Guess you like

Origin www.cnblogs.com/yrash/p/11319357.html