本节内容

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. DrangonBorns

    团队介绍 团队名称:DrangonBorns(龙裔)      团队博客:http://www.cnblogs.com/DragonBorns/     团队队长:蒲建国     队长博客链接:htt ...

  2. MYSQL InnoDB Cluster

    https://dev.mysql.com/doc/refman/5.7/en/group-replication.html GroupReplication的原理 https://dev.mysql ...

  3. Server Tomcat v7.0 Server at libra failed to start

    https://stackoverflow.com/questions/13244233/server-tomcat-v7-0-server-at-localhost-failed-to-start- ...

  4. MYSQL CASCADE DELETE 引发的思考

    MYSQL CASCADE DELETE :级联删除.这个概念还是学习Oracle时得到的. 就是主键记录删除时,相关的有外键的表里的记录,也删除. https://dev.mysql.com/doc ...

  5. vue 路由传参 params 与 query两种方式的区别

    初学vue的时候,不知道如何在方法中跳转界面并传参,百度过后,了解到两种方式,params 与 query.然后,错误就这么来了:  router文件下index.js里面,是这么定义路由的: { p ...

  6. FICO基础知识(一)

    GL – 总账 (General Ledger) 总帐核算的中心任务是提供外部会计及其所涉及帐户的概貌. 总账会计主要用途:根据不同的会计准则(如欧洲的 IAS, 美国的GAAP, 中国国家会计准则) ...

  7. vue-cli webpack项目npm run dev启动过程

    前言 通过vue init webpack和npm install命令初始化项目后,执行npm run dev就打开了网站http://localhost:8080.初学者不知道index.html. ...

  8. 训练题(代码未检验)(序列前k大和问题)

    大厦 Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other) Total Submission ...

  9. ZJOI2019 Day1游记

    退役吧垃圾 考的再烂还是要把自己捡起来 如果不想让自己的OI生涯就到这里止步的话 就给我滚去拿剩下的300分吧 浙江省前十六,学校前五,day1比别人差一百多分.如果这样还能进省队的话,我就成为传说了 ...

  10. 全球最大轻博客APP确认被苹果下架!

    读 苹果确认了App Store下架轻博客应用Tumblr,主要原因是,该应用没有很好的过滤掉一些成人内容(成人内容多到夸张),这严重影响了未成年人. 事实上,iPhone和iPad版Tumblr应用 ...