config:配置    parser:解析

此模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser,在 python 2.x 里名字为 ConfigParer

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

```cnf
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no
```

解析

```py
>>> import configparser # 导入模块
>>> config = configparser.ConfigParser() #实例化(生成对象)
>>> config.sections() #调用sections方法
[]
>>> config.read('example.ini') # 读配置文件(注意文件路径)
['example.ini']
>>> config.sections() #调用sections方法(默认不会读取default)
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config #判断元素是否在sections列表内
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User'] # 通过字典的形式取值
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
''
>>> for key in config['bitbucket.org']: print(key) # for循环 bitbucket.org 字典的key
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
```

其他增删改查语法

import configparser

config = configparser.ConfigParser()
config.read('conf_test.ini') ########## 读 ##########
secs = config.sections() #获取结点的值
print(secs)
options = config.options('group2') # 获取指定section的keys
print(options) item_list = config.items('group2') # 以元组的形式获取指定 section 的 keys & values ,key value
print(item_list) val = config.get('group1','key') # 获取指定的key 的value
val = config.getint('group1','key') # 获取指定key 的value ,其中value必须为 int 类型 ########## 改写 ##########
sec = config.remove_section('group1') # 删除section 并返回状态(true, false)
config.write(open('conf_test.ini', "w")) # 每个对应的修改操作都要写入文件才会生效 sec = config.has_section('wupeiqi') #section 中是否存在 wupeiqi
sec = config.add_section('wupeiqi') #添加section
config.write(open('conf_test.ini', "w")) config.set('group2','k1','') #向section中添加key及其对应value,其中key和value都必须是str
config.write(open('conf_test.ini', "w")) config.remove_option('group2','age') #删除指定section中的指定key及其对应value值
config.write(open('conf_test.ini', "w"))

最新文章

  1. AOP的实现原理
  2. Linux Socket编程
  3. ON DUPLICATE KEY UPDATE重复插入时更新
  4. HTML 学习笔记 JavaScript (对象)
  5. Android错误:W/ResourceType(2411): No package identifier when getting value for resource number 0x
  6. Carath\'eodory 不等式
  7. iOS模拟器分辨率的问题(转载)
  8. 编写高质量iOS代码的52个有效方法1-1
  9. Unbutu14.04 切换ROOT用户后无法启用音频
  10. Ant 之bulid.xml详解
  11. 关于数据库timestamp类型问题
  12. PageContext ServletContext ServletConfig辨析
  13. spring-cloud-config安全问题
  14. vue cli 3.x 项目部署到 github pages
  15. Loj #2321. 「清华集训 2017」无限之环
  16. TabLayout的高级使用
  17. 使用Oracle BBED修改Oracle11g数据库实例名称
  18. C#ConcurrentDictionary源代码
  19. 【BZOJ】3143: [Hnoi2013]游走
  20. P2824 [HEOI2016/TJOI2016]排序

热门文章

  1. Spring Boot:定时任务
  2. Mxnet编译安装
  3. 8ci
  4. Tomcat各个版本下载路径
  5. linux链接及文件互相上传下载
  6. 初写Linux脚本坑记录
  7. js 发送http请求
  8. selenium 分布式 [WinError 10061] 由于目标计算机积极拒绝
  9. Vue语法学习第三课——计算属性
  10. 推理机Jess,Racer,Jena