Python(configparser模块)

configparser模块 (37min day18)

 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 
 5 config["DEFAULT"] = {'ServerAliveInterval': '45',
 6                      'Compression': 'yes',
 7                      'CompressionLevel': '9'}
 8 #
 9 # config['bitbucket.org'] = {}
10 #
11 # config['bitbucket.org']['User'] = 'hg'
12 config['bitbucket.org'] = {'User':'hg'} #与上面一致
13 
14 
15 config['topsecret.server.com'] = {}
16 
17 topsecret = config['topsecret.server.com']
18 topsecret['Host Port'] = '50022'  # mutates the parser
19 topsecret['ForwardX11'] = 'no'  # same here
20 
21 config['DEFAULT']['ForwardX11'] = 'yes'
22 
23 with open('example.ini', 'w') as configfile: #创建,写
24     config.write(configfile)
25 
26 #
27 config.read('example.ini')
28 print(config.sections()) #默认的不读出
29 print(config.defaults()) #有序字典
30 print('')
31 print(config['bitbucket.org']['User'])
32 print('')
33 for key in config['bitbucket.org']:
34     print(key) #本来只能输出 user键,但是默认的键也输出
35 print('')
36 config.remove_section('topsecret.server.com')
37 
38 print(config.has_section('topsecret.server.com')) #已被删,无法找到
39 
40 config.set('bitbucket.org','user','alex')#修改值
41 
42 config.write(open('i.cfg',"w"))#也可以写成同名文件example.ini,但那属于覆盖,不属于删除

执行结果:

['bitbucket.org', 'topsecret.server.com']
OrderedDict([('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'yes')])

hg

user
compressionlevel
serveraliveinterval
compression
forwardx11

False

Process finished with exit code 0

生成的example.ini文件

[DEFAULT]
compressionlevel = 9
serveraliveinterval = 45
compression = yes
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no

生成的i.cfg文件

[DEFAULT]
compressionlevel = 9
serveraliveinterval = 45
compression = yes
forwardx11 = yes

[bitbucket.org]
user = alex

参考:http://www.cnblogs.com/alex3714/articles/5161349.html

猜你喜欢

转载自www.cnblogs.com/112358nizhipeng/p/9573660.html
今日推荐