configparser模块的特点和用法

一、概述

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

二、格式

  常见配置文件格式如下:

 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 host port = 50022
12 forwardx11 = no

三、主要用法

1、创建配置文件

 1 import  configparser   #导入configparser模块
 2
 3 #生成一个对象
 4 config = configparser.ConfigParser()
 5 #配置默认全局配置组
 6 config["DEFALUT"] = {"ServerAliveInterval":"45",
 7                       "Compression":"yes",
 8                       "CompressionLevel":"9"
 9                       }
10 #配置第一个其他组
11 config["bitbucket.org"] = {}
12 #直接赋值
13 config["bitbucket.org"]["User"] = 'hg'
14
15 #配置第二个其他组
16 config["topsecret.server.com"] = {}
17 #这边就赋给一个变量
18 topsecret = config["topsecret.server.com"]
19 #通过变量赋值
20 topsecret["Host Port"] = '50022'
21 topsecret["ForwardX11"] = 'no'
22 #给全局配置组赋值
23 config["DEFALUT"]["ForwardX11"] = "yes"
24 #操作完毕,把配置的内容写入一个配置文件中
25 with open("example.ini","w") as configfile:
26     config.write(configfile)

2、读取配置文件

1)、读取配置组

 1 >>> import  configparser
 2 >>> config = configparser.ConfigParser()
 3 >>> config.sections()    #不读取配置文件,组名列表为空
 4 []
 5 >>> config.read("example.ini")  #读取配置文件,返回配置文件名
 6 ['example.ini']
 7 >>> config.sections()  #返回除默认配置组的其他组名
 8 ['bitbucket.org', 'topsecret.server.com']
 9 >>> config.defaults()   #读取默认配置组,并返回有序字典
10 OrderedDict([('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'yes')])

2)、组名是否存在

1 >>> 'bitbucket.org' in config   #组名存在
2 True
3 >>> 'zhangqigao.org'  in config   #组名不存在
4 False

3)、读取组内的值

1 >>> config["bitbucket.org"]["User"]  #读取"bitbucket.org"配置组中的值
2 'hg'
3 >>> config["DEFAULT"]["Compression"]  #读取默认配置组中的值
4 'yes'
5 >>> topsecret = config['topsecret.server.com']  #把配置组赋给一个对象
6 >>> topsecret['ForwardX11']   #通过对象获取值

4)、 循环获取组内的key值

 1 >>> for key in config["bitbucket.org"]:  #循环打印bitbucket.org组下的key值
 2 ...     print(key)
 3 ...
 4 #输出,只打印默认组和bitbucket.org组的key值
 5 user
 6 compressionlevel
 7 serveraliveinterval
 8 compression
 9 forwardx11
10 >>> for key in config["topsecret.server.com"]:#循环打印topsecret.server.com组下的key值
11 ...     print(key)
12 ...
13 #输出,只打印默认组和topsecret.server.com组的key值
14 host port
15 forwardx11
16 compressionlevel
17 serveraliveinterval
18 compression

重点:

四、configparser增删改查语法

1、配置文件名i.cfg

1
2
3
4
5
6
7
8
9
10
[DEFAULT]
k1 = v1
k2 = v2
[section1]
k3 = v3
k4:v4
[section2]
k5 = 5

2、读i.cfg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import configparser
config = configparser.ConfigParser()
config.read("i.cfg")
sec = config.sections()
print(sec)
#输出
['section1''section2']
options = config.options("section2")  #返回默认组和section2组的key值
print(options)
#输出
['k5''k1''k2']
item_list = config.items("section2")   #返回默认组和section2组的key-value值
print(item_list)
#输出
[('k1''v1'), ('k2''v2'), ('k5''5')]
val1 = config.get("section2","k1")   #获取section2组中k1对应的值,是否可取是按照上面返回的列表
print(val1)
#输出
v1
val2  = config.getint("section2","k5")  #返回section2中k5的值,这个值返回的int类型的
print(val2)
#输出
5

3、改写i.cfg

①删除section和option

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import configparser
config = configparser.ConfigParser()
config.read("i.cfg")
config.remove_option("section1","k3")  #删除section1组下的k3
config.remove_section("section2")   #删除section2组
with open("i.cfg2","w") as f:   #重新写入一个文件
    config.write(f)
#输出,写入文件的内容
[DEFAULT]
k1 = v1
k2 = v2
[section1]
k4 = v4

②添加section

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import configparser
config = configparser.ConfigParser()
config.read("i.cfg")
sec = config.has_option("section2","k5")  #是否存在section2组内有k5
print(sec)
#输出
True
sec = config.has_section("duoduo")  #是否存在duoduo组
print(sec)
#输出
False
config.add_section("duoduo")  #添加section组duoduo
config.add_section("duoduo")  #重新写入到一个配置文件中
with open("i.cfg3","w") as f:
    config.write(f)

③添加或者设置option

1
2
3
4
5
6
7
8
9
import configparser
config = configparser.ConfigParser()
config.read("i.cfg")
config.set("duoduo","z","18")  #设置或者添加duoduo中option值
with open("i.cfg3","w") as f:   #重新写入文件中
    config.write(f)

转载于:https://www.cnblogs.com/ManyQian/p/8353436.html

小白的Python之路 day5 configparser模块的特点和用法相关推荐

  1. Python 之路 Day5 - 常用模块学习

    模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configparser has ...

  2. Python小白的进阶之路---Day5

    Python小白的进阶之路---Day5 1.file 1.1打开文件方式(读写两种方式) 1.2文件对象的操作方法 1.3学习对excel及csv文件进行操作 2.os模块 3.datatime模块 ...

  3. 运维小白的python之路(一)

    运维小白的python之路(一) 本人运维小白一枚,目前在负责某银行的测试服务器的基础运维.浑浑噩噩的过了一年,工作上也涉及不到什么技术.身边的朋友们都在各自的领域内奋斗发展,感觉自己不能这样下去了, ...

  4. python中configparser_python中confIgparser模块学习

    python中configparser模块学习 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section ...

  5. python生成配置文件config_Python configparser模块封装及构造配置文件

    1.configparser模块简介 使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是configP ...

  6. python之路 day5

    http://www.cnblogs.com/wupeiqi/articles/4963027.html 最近一直忙,这次决定抽出时间,把博客写好.博客好处多多这里就不说了,开写. 今天学习的主要内容 ...

  7. 白白的python之路--Day5

    5一.使用列表 list:列表也是一种结构化的.非标量类型,它是值的有序序列,每个值都可以通过索引进行标识,定义列表可以将列表的元素放在[]中,多个元素用,进行分隔,可以使用for循环对列表元素进行遍 ...

  8. python之路day5_学习python之路--Day5 计算器

    需求 可以处理带括号的加减乘除运算 需求分析 匹配括号 re.search('\(.*\)',a) 匹配最里面括号 re.search(r'\([^()]+\)') 可以用strip()方法去掉括号 ...

  9. 小白的python之路Linux部分10/2829

    属主属组其他人对文件的rwx权限 1.userdel删东西不全,会有残留, 彻底删除[root@localhost ~]# userdel -r tom 单个删除[root@localhost ~]# ...

最新文章

  1. Observer观察者设计模式
  2. go语言int类型转化成string类型的方式
  3. 在django中使用celery
  4. 基于.NetCore3.1搭建项目系列 —— 使用Swagger做Api文档 (下篇)
  5. 欧洲的数据中心与美国的数据中心如何区分?
  6. javascript一些面试常用的问题总结
  7. NYOJ题目1170-最大的数
  8. thinkphp5.1合成带二维码海报图片
  9. 奇偶校验方法(韦根协议)
  10. 高效上网教程---如何免费下载全网中英文论文
  11. 【电力电子技术】浅析IR2110自举电路
  12. 【案例学习】最大锁具制造商怎样使用 Docker?
  13. 使用R语言制作树状图
  14. C语言练习——基础篇
  15. NUVOTON-MS51FB9AE规格书方案
  16. 硬盘那些事(Windows系统下磁盘格式的优缺点)
  17. Echarts柱状图柱子上“画线”
  18. 计算机二级c语言模拟上机,计算机二级C语言上机模拟题
  19. 生物信息学|深度学习改善了药物药物相互作用和药物食物相互作用的预测精度
  20. 外部接口调用失败重试

热门文章

  1. 猴子选大王c语言课程设计,【C/C++】猴子选大王
  2. 云计算机教室安装学生软件,新东方云教室1.6版本
  3. app上传头像处理Java_java后台加安卓端实现头像上传功能
  4. numpy更改形状、类型
  5. c语言结构体赋值,并输出各种类型变量的值
  6. 实训说明书 在线音乐平台项目规格说明书
  7. 干货|如何在无回显时渗透
  8. 【slighttpd】基于lighttpd架构的Server项目实战(7)—http-parser
  9. 读WAF与IPS的区别总结之摘抄
  10. 20-forEach循环语句