configparser模块(* *)

来看一个好多软件的常见文档格式如下:

 1 [DEFAULT]
 2 ServerAliveInterval = 45
 3 Compression = yes
 4 CompressionLevel = 9
 5 ForwardX11 = yes
 6   
 7 [bitbucket.org]
 8 User = hg
 9   
10 [topsecret.server.com]
11 Port = 50022
12 ForwardX11 = no

如果想用python生成一个这样的文档怎么做呢?

 1 import configparser
 2   
 3 config = configparser.ConfigParser()
 4 config["DEFAULT"] = {'ServerAliveInterval': '45',
 5                       'Compression': 'yes',
 6                      'CompressionLevel': '9'}
 7   
 8 config['bitbucket.org'] = {}
 9 config['bitbucket.org']['User'] = 'hg'
10 config['topsecret.server.com'] = {}
11 topsecret = config['topsecret.server.com']
12 topsecret['Host Port'] = '50022'     # mutates the parser
13 topsecret['ForwardX11'] = 'no'  # same here
14 config['DEFAULT']['ForwardX11'] = 'yes'
15 with open('example.ini', 'w') as configfile:
16    config.write(configfile)
 1 #增删改查
import configparser 2 3 config = configparser.ConfigParser() 4 5 #---------------------------------------------查 6 print(config.sections()) #[] 7 8 config.read('example.ini') 9 10 print(config.sections()) #['bitbucket.org', 'topsecret.server.com'] 11 12 print('bytebong.com' in config)# False 13 14 print(config['bitbucket.org']['User']) # hg 15 16 print(config['DEFAULT']['Compression']) #yes 17 18 print(config['topsecret.server.com']['ForwardX11']) #no 19 20 21 for key in config['bitbucket.org']: 22 print(key) 23 24 25 # user 26 # serveraliveinterval 27 # compression 28 # compressionlevel 29 # forwardx11 30 31 32 print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11'] 33 print(config.items('bitbucket.org')) #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')] 34 35 print(config.get('bitbucket.org','compression'))#yes 36 37 38 #---------------------------------------------删,改,增(config.write(open('i.cfg', "w"))) 39 40 41 config.add_section('yuan') 42 43 config.remove_section('topsecret.server.com') 44 config.remove_option('bitbucket.org','user') 45 46 config.set('bitbucket.org','k1','11111') 47 48 config.write(open('i.cfg', "w"))

 原文链接:https://www.cnblogs.com/yuanchenqi/articles/5732581.html

原文地址:https://www.cnblogs.com/jiawen010/p/9927950.html