本节内容

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. Linux添加目录到环境变量以及添加sublime到环境变量

    博主之前有过这种情况,就是在普通用户下su ls等命令还有效,可登陆进root用户之后这些常用的命令竟然失效了. 像这样 这问题其实很简单,但是对于不清楚环境变量的配置的同学来说也的确棘手,我之前就是 ...

  2. [读书笔记]Linux命令行与shell编程读书笔记01

    1. Linux的组成部分 1)linux内核(kernel) 2)GNU工具链 3)GUI/CLI工作几面(shell) 4)应用程序(app) 2Linux内核的主要工作: 1) 管理内存 2)管 ...

  3. MySQL-如何删除hash表分区

    一个大表,之前是以hash分区表的形式存在的, MySQL> show create table history_uint; | history_uint | CREATE TABLE `his ...

  4. LODOP中平铺图片 文本项Repeat

    Lodop打印控件中,可使用如下语句让打印项平铺在纸张上.LODOP.SET_PRINT_STYLEA(0,"Repeat",true);平铺的打印项的区域和打印项的宽高有关,如图 ...

  5. Windows 增加远程连接数

    转载自 https://blog.csdn.net/scholar_man/article/details/60570827 1.设置终端设置,需要打开[控制面板]---[系统和安全] 2.进入系统和 ...

  6. 利用可变参数打印log2

    #pragma once #include <string> #include "StdAfx.h" #include <Windows.h> using ...

  7. BZOJ4942 NOI2017整数(线段树)

    首先把每32位压成一个unsigned int(当然只要压起来能过就行).如果不考虑进/退位的话,每次只要将加/减上去的数拆成两部分直接单点修改就好了.那么考虑如何维护进/退位.可以发现进位的过程其实 ...

  8. POJ1611-The Suspects-并查集

    记录元素个数的并查集. 利用sz数组保存并查集的大小.每次union时,把小的集合并到大的中去,并更新sz数组. #include <cstdio> #include <algori ...

  9. Git分支合并

    大致描述一下 上次为了解决bug新建了一个bugfix分支,并提交了c5(这个1,2,3,4,5具体的可能和图片对应不太一样,但是结构一样),下面就该把bugfix与master进行整合,整合之后就可 ...

  10. linux保存住github的账号和密码

    我是用 shell 命令来执行 git 操作的,所以就决定在 --global 配置一下用户名和密码,不用每次手动输入了. 设置步骤 1. 首先需要 ftp 连接到你的 Linux 服务器,在根目录( ...