configparser模块的特点和用法

一、概述

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

二、格式

  常见配置文件格式如下:

 [DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes [bitbucket.org]
user = hg [topsecret.server.com]
host port = 50022
forwardx11 = no

三、主要用法

1、创建配置文件

 import  configparser   #导入configparser模块

 #生成一个对象
config = configparser.ConfigParser()
#配置默认全局配置组
config["DEFALUT"] = {"ServerAliveInterval":"",
"Compression":"yes",
"CompressionLevel":""
}
#配置第一个其他组
config["bitbucket.org"] = {}
#直接赋值
config["bitbucket.org"]["User"] = 'hg' #配置第二个其他组
config["topsecret.server.com"] = {}
#这边就赋给一个变量
topsecret = config["topsecret.server.com"]
#通过变量赋值
topsecret["Host Port"] = ''
topsecret["ForwardX11"] = 'no'
#给全局配置组赋值
config["DEFALUT"]["ForwardX11"] = "yes"
#操作完毕,把配置的内容写入一个配置文件中
with open("example.ini","w") as configfile:
config.write(configfile)

2、读取配置文件

1)、读取配置组

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

2)、组名是否存在

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

3)、读取组内的值

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

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

 >>> for key in config["bitbucket.org"]:  #循环打印bitbucket.org组下的key值
... print(key)
...
#输出,只打印默认组和bitbucket.org组的key值
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> for key in config["topsecret.server.com"]:#循环打印topsecret.server.com组下的key值
... print(key)
...
#输出,只打印默认组和topsecret.server.com组的key值
host port
forwardx11
compressionlevel
serveraliveinterval
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)

小白的Python之路 day5 configparser模块的特点和用法的更多相关文章

  1. 小白的Python之路 day5 logging模块

    logging模块的特点及用法 一.概述 很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你 ...

  2. 小白的Python之路 day5 random模块和string模块详解

    random模块详解 一.概述 首先我们看到这个单词是随机的意思,他在python中的主要用于一些随机数,或者需要写一些随机数的代码,下面我们就来整理他的一些用法 二.常用方法 1. random.r ...

  3. 小白的Python之路 day5 shelve模块讲解

    shelve模块讲解 一.概述 之前我们说不管是json也好,还是pickle也好,在python3中只能dump一次和load一次,有什么方法可以向dump多少次就dump多少次,并且load不会出 ...

  4. 小白的Python之路 day5 hashlib模块

    hashlib模块 一.概述 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法 二.算法的演 ...

  5. 小白的Python之路 day5 shutil模块

    shutil模块 一.主要用途 高级的文件.文件夹.压缩包 等处理模块 二.常用方法详解 1.shutil.copyfileobj(fsrc, fdst) 功能:把一个文件的内容拷贝到另外一个文件中, ...

  6. 小白的Python之路 day5 模块XML特点和用法

    模块XML的特点和用法 一.简介 xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今 ...

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

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...

  8. python 之路 day5 - 常用模块

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

  9. Python之路,Day5 - 常用模块学习 (转载Alex)

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...

随机推荐

  1. Linux发行版 CentOS6.5 修改默认主机名

    修改前准备 我们将主机名修改为comexchan.cnblogs.com(本文发布于http://comexchan.cnblogs.com/) 备份相关配置文件,以便回滚 cp /etc/sysco ...

  2. h5拖拽上传图片

    h5实现拖拽上传图片 本文将为大家介绍如何通过js实现拖拽上传图片. 首先我们要禁用调浏览器默认的拖拽事件: window.onload = function(){ //拖离 document.add ...

  3. Dotnet Core Windows Service

    在dotnet 中有topshelf 可以很方便的写windows 服务并且安装也是很方便的,命令行 运行.exe install 就直接把exe 程序安装成windows 服务.当然 代码也要做相应 ...

  4. Runtime那些事

    Runtime 前言 从字面意思看,就是运行时.但是这个运行时究竟什么意思?可以把它理解成:不是在编译期也不是在链接期,而是在运行时.那究竟在运行期间做了什么呢?按照苹果官方的说法,就是把一些决策(方 ...

  5. MicroPython-TPYBoard固件编译教程

    本文主要介绍一下,在Linux环境下编译micropython固件的方法和流程. 首先,我们先来看一下MicroPython的源码结构. github地址:https://github.com/mic ...

  6. Maven代理设置

    公司需要设置代理才能上网,而运行Maven时需要下载依赖的库. 怎么办呢? 原来Maven也像IE一样,可以设置HTTP代理的. 步骤如下: ·编辑 ~/.m2/setting.xml 文件.如果该目 ...

  7. PE文件解析器的编写(二)——PE文件头的解析

    之前在学习PE文件格式的时候,是通过自己查看各个结构,自己一步步计算各个成员在结构中的偏移,然后在计算出其在文件中的偏移,从而找到各个结构的值,但是在使用C语言编写这个工具的时候,就比这个方便的多,只 ...

  8. 在树莓派上编译安装golang环境

    请看我在掘金的文章

  9. spring的父子容器

    在创建ssm项目工程时,经常需要读取properties资源配置文件,传统的方法当然可以. 但是spring提供了更简便的方法,@value注解. 在page.properties文件中,配置分页信息 ...

  10. vue路由对象($route)参数简介

    路由对象在使用了 vue-router 的应用中,路由对象会被注入每个组件中,赋值为 this.$route ,并且当路由切换时,路由对象会被更新. so , 路由对象暴露了以下属性: 1.$rout ...