一、創建文件
1 ##-----------------創建數據表--------------------------
2 import configparser 3 config = configparser.ConfigParser() 4
5 config["DEFAULT"] = { 6 'ServerAliveInterval': '45', 7 'Compression': 'yes', 8 'CompressionLevel': '9'
9 } 10
11 config["bitbucket.org"] = {} 12 config["bitbucket.org"]["user"] = "hg"
13
14 config['topsecret.server.com'] = {} 15 topsecret = config['topsecret.server.com'] # ?
16 topsecret['Host Post'] = '50022' #mutates the parser
17 topsecret['ForwardX11'] = 'no' #same here
18
19 with open('example.ini','w') as f: 20 config.write(f)
2、增刪改查--查
1 ###----------增刪改查------------------------------
2 import configparser 3 config = configparser.ConfigParser() 4
5
6 print(config.sections()) # 返回空列表[]
7 # print(config.user())
8 ##------------> 查
9 config.read('example.ini') 10 print(config.sections()) #['bitbucket', 'topsecret.server.com']
11
12 print('bytebong.com' in config) #False
13 print(config['bitbucket.org']['user']) # hg
14
15 print(config['topsecret.server.com']['host post']) #50022
16 print(config['topsecret.server.com']['forwardx11']) #no
17 print(config['DEFAULT']['serveraliveinterval']) #45
18
19 for key in config['bitbucket.org']: 20 print('【bit】',key) 21
22 print(config.options('bitbucket.org')) # ??['user', 'serveraliveinterval', 'compression', 'compressionlevel']
23 print(config.items('bitbucket.org')) #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('user', 'hg')]
24 ## 下面的兩組,不管取哪個,都會把[DEFAULT] 里面的順帶打印出來,這以后在實際中有相應的應用、
25
26 print(config.get('bitbucket.org','compression')) #?? yes
3、增、改、刪
1 ##------> 刪、改、增
2 config.add_section('zhao') # 增加一條
3 config.set('zhao','key','python') 4
5 config.remove_section('topsecret.server.com') 6 config.remove_option('bitbucket.org','user') 7
8 config.write(open('zhao',"w"))