configparser (配置文件) 模块

主要内容来自景女神博客

内涵:该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

常见文档格式:

 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
View Code

如何生成文档格式:

 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 
 5 config["DEFAULT"] = {'ServerAliveInterval': '45',
 6                       'Compression': 'yes',
 7                      'CompressionLevel': '9',
 8                      'ForwardX11':'yes'
 9                      }
10 
11 config['bitbucket.org'] = {'User':'hg'}
12 
13 config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
14 
15 with open('example.ini', 'w') as configfile:
16 
17    config.write(configfile)
View Code

查找文件:

 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 
 5 #---------------------------查找文件内容,基于字典的形式
 6 
 7 print(config.sections())        #  []
 8 
 9 config.read('example.ini')
10 
11 print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']
12 
13 print('bytebong.com' in config) # False
14 print('bitbucket.org' in config) # True
15 
16 
17 print(config['bitbucket.org']["user"])  # hg
18 
19 print(config['DEFAULT']['Compression']) #yes
20 
21 print(config['topsecret.server.com']['ForwardX11'])  #no
22 
23 
24 print(config['bitbucket.org'])          #<Section: bitbucket.org>
25 
26 for key in config['bitbucket.org']:     # 注意,有default会默认default的键
27     print(key)
28 
29 print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
30 
31 print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
32 
33 print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value
34 复制代码
View Code

增删改查操作:

 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 
 5 config.read('example.ini')
 6 
 7 config.add_section('yuan')
 8 
 9 
10 
11 config.remove_section('bitbucket.org')
12 config.remove_option('topsecret.server.com',"forwardx11")
13 
14 
15 config.set('topsecret.server.com','k1','11111')
16 config.set('yuan','k2','22222')
17 
18 config.write(open('new2.ini', "w"))
View Code

 

转载于:https://www.cnblogs.com/ipyanthony/p/9306087.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值