本节内容

1、简述

2、配置文件格式

3、创建配置文件

4、读取配置文件

5、增删该查语法

一、简述

  在很多情况下,我们都需要修改配置文件,但是,有些配置文件,如mysql数据库的配置文件怎么修改呢?我们今天就来写一下,用于生产和修改常见配置文件的模块:configparser。

二、配置文件格式

1、配置文件格式

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

三、创建配置文件

1、创建配置文件

说明:其实有的时候我们很少创建,除非是用系统管理,一般直接修改就可以了,但是还是要掌握的。

代码如下:

import  configparser   #导入configparser模块

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

四、读取配置文件

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', '9'), ('serveraliveinterval', '45'), ('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'] #通过对象获取值
'no

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

注:默认组是全局的,所以循环遍历key值时,会遍历从默认组和需要遍历的组一起遍历出来。

五、configparser增删改查语法

1、配置文件名i.cfg

[DEFAULT]
k1 = v1
k2 = v2 [section1]
k3 = v3
k4:v4 [section2]
k5 = 5

2、读i.cfg

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

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

import configparser

config = configparser.ConfigParser()
config.read("i.cfg")
sec = config.has_option("section2","k5") #是否存在section2组内有k5
print(sec)
#输出
True sec = config.has_section("zhangqigao") #是否存在zhangqigao组
print(sec)
#输出
False config.add_section("zhangqigao") #添加section组zhangqigao config.add_section("zhangqigao") #重新写入到一个配置文件中
with open("i.cfg3","w") as f:
config.write(f)

③添加或者设置option

import configparser

config = configparser.ConfigParser()
config.read("i.cfg") config.set("zhangqigao","z","18") #设置或者添加zhangqigao中option值 with open("i.cfg3","w") as f: #重新写入文件中
config.write(f)

函数和常用模块【day06】:configparser模块(七)的更多相关文章

  1. python基础14 ---函数模块4(configparser模块)

    configparser模块 一.configparser模块 1.什么是configparser模块:configparser模块操作配置文件,配置文件的格式与windows ini和linux的c ...

  2. Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 一.前言 我们在<中我们描述了Python数据持久化的大体概念和基本处理方式,通过这些知识点我们已经 ...

  3. 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    [转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...

  4. [xml模块、hashlib模块、subprocess模块、os与sys模块、configparser模块]

    [xml模块.hashlib模块.subprocess模块.os与sys模块.configparser模块] xml模块 XML:全称 可扩展标记语言,为了能够在不同的平台间继续数据的交换,使交换的数 ...

  5. python常用模块之configparser模块

    python常用模块之configparser 作用:解析配置文件 假设在当前目录下有这样一个conf.ini文件 [DEFAULT] ServerAliveInterval = 45 Compres ...

  6. os模块、os.path模块、shutil模块、configparser模块、subprocess模块

    一.os模块 os指的是操作系统 该模块主要用于处理与操作系统相关的操作,常用的是文件操作(读.写.删.复制.重命名). os.getcwd()  获取当前文件所在的文件夹路径 os.chdir()  ...

  7. 《Python》hashlib模块、configparser模块、logging模块

    一.hashlib模块 Python的hashlib模块中提供了常见的摘要算法,如md5,sha1等等. 摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的字符串(通 ...

  8. 模块二 hashlib模块、configparser模块、logging模块

    算法介绍 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常 ...

  9. Python day21模块介绍4(logging模块,configparser模块)

    1.日志等级从上往下依次降低 logging.basicConfig(#日志报错打印的基础配置 level=logging.DEBUG, filename="logger.log" ...

  10. day5模块学习--configparser模块

       使用ConfigParser模块读写ini文件(http://blog.csdn.net/linda1000/article/details/11729561) ConfigParserPyth ...

随机推荐

  1. java中字符串的排序(1)

    按照前段时间在快速.冒泡等排序的评论中提到是否可以进行字符串的排序,由于最近有考试,时间比较紧,所以今天才实现此功能.此功能是针对一串字符川进行的实现,运行后的结果如下所示: 具体的程序相对较为简单, ...

  2. java 值传递 数组传递

    在java中,不允许程序员选择值传递还是地址传递各个参数,基本类型总是按值传递.对于对象来说,是将对象的引用也就是副本传递给了方法,在方法中只有对对象进行修改才能影响该对象的值,操作对象的引用时是无法 ...

  3. solt插槽的使用。

    在组件内template中使用 <slot name='header'></slot> 在页面内 直接添加标签 如 <hs><h1 slot='header' ...

  4. Oracle18c OnlyExadataVersion 安装说明

    1.根据惜分飞还有盖国强老师云和恩墨的文章, 验证了下OnlyExadataVersion的Oracle18c的数据库安装过程. 2.oracle参数修改以及创建用户, 目录, 修改.bash_pro ...

  5. [转帖]召冠总的 SQLSERVER常用的性能诊断语句. --保存学习备查

    CopyFrom https://www.cnblogs.com/zhaoguan_wang /*常规服务器动态管理对象包括:dm_db_*:数据库和数据库对象dm_exec_*:执行用户代码和关联的 ...

  6. html 背景

    用語設置背景的屬性 bgcolor設置背景顏色.可以使用名字.16進制和rgb三種形式的參數: <body bgcolor="#000000"> <body bg ...

  7. Lodop导出excel及提示成功【回调和直接返回值】

    高版本的火狐和谷歌不再支持np插件之后,Lodop公司推出了C-Lodop,解决了这些浏览器不能用Lodop插件方式打印的问题,相比较Lodop插件,C-Lodop由于是以服务的形式出现,返回值不能直 ...

  8. map()实现zip()功能

    c = (map(lambda x,y:(x,y),[1,2,3],["abd","def","ghi"]))print(list(c)) ...

  9. 微软开放 6 万项 Linux 专利,有哪些是我们该注意的?

    导读 上周,微软宣布正式加入 Open Invention Network (“OIN”) 社区,开放其 6 万多项 Linux 专利.消息一出,许多人疑惑微软为什么要这么做?作为普通开发者,是否能使 ...

  10. cxf 方法添加注解

    /** * 登录 * @param uid * @param password * @return */ @POST @Path(value = "/login") public ...