博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
configparser模块
阅读量:4573 次
发布时间:2019-06-08

本文共 1953 字,大约阅读时间需要 6 分钟。

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

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

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

 

解析配置文件

```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 configFalse>>> config['bitbucket.org']['User'] # 通过字典的形式取值'hg'>>> config['DEFAULT']['Compression']'yes'>>> topsecret = config['topsecret.server.com']>>> topsecret['ForwardX11']'no'>>> topsecret['Port']'50022'>>> for key in config['bitbucket.org']: print(key) # for循环 bitbucket.org 字典的key...usercompressionlevelserveraliveintervalcompressionforwardx11>>> config['bitbucket.org']['ForwardX11']'yes'```
View Code

 

 

其它增删改查语法

```python[group1] # 支持的两种分隔符“=”, “:”k1 = v1k2:v2[group2]k1 = v1import ConfigParserconfig = ConfigParser.ConfigParser()config.read('i.cfg')# ########## 读 ###########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')# ########## 改写 ###########sec = config.remove_section('group1') # 删除section 并返回状态(true, false)#config.write(open('i.cfg', "w")) # 对应的删除操作要写入文件才会生效#sec = config.has_section('wupeiqi')#sec = config.add_section('wupeiqi')#config.write(open('i.cfg', "w")) # #config.set('group2','k1',11111)#config.write(open('i.cfg', "w"))#config.remove_option('group2','age')#config.write(open('i.cfg', "w"))```
View Code

 

转载于:https://www.cnblogs.com/baoguniang/p/9849353.html

你可能感兴趣的文章
iOS 字体下载
查看>>
Distinct
查看>>
INFO hdfs.DFSClient: Exception in createBlockOutputStream java.net解决办法
查看>>
SQL 循环语句
查看>>
XML文档
查看>>
Java 泛型
查看>>
定义页面加载和导航时要执行的函数/自定义事件
查看>>
rem.js
查看>>
Unslider.js Tiny Sample
查看>>
FPGA的学习及注意事项
查看>>
关于python中,map,reduce,filter,sort函数的用法:
查看>>
面向对象内存分析
查看>>
Dijkstra BZOJ2763 [JLOI2011]飞行路线
查看>>
前端快捷键
查看>>
重新认识成功、失败、错误、平凡、笨拙
查看>>
【模板】Hash
查看>>
洛谷 1485 火枪打怪
查看>>
Fortran编译器
查看>>
初识go
查看>>
将一张表中的部分记录插入到另一张表中
查看>>