主要介绍python3中的ConfigParser模块的使用,该模块主要被用来读写配置文件。

安装模块:pip3 install configparser

root@ranxf:/usr/lib/python3/dist-packages# pip3 install configparser
Collecting configparser
Downloading configparser-3.5.0.tar.gz
Building wheels for collected packages: configparser
Running setup.py bdist_wheel for configparser ... done
Stored in directory: /root/.cache/pip/wheels/1c/bd/b4/277af3f6c40645661b4cd1c21df26aca0f2e1e9714a1d4cda8
Successfully built configparser
Installing collected packages: configparser
Successfully installed configparser-3.5.0

基本的读取配置文件

    -read(filename)                  直接读取文件内容

    -sections()                      得到所有的section,并以列表的形式返回

    -options(section)                得到该section的所有option

    -items(section)                  得到该section的所有键值对

    -get(section,option)             得到section中option的值,返回为string类型

    -getint(section,option)          得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

基本的写入配置文件

    -add_section(section) 添加一个新的section

    -set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

在对配置文件进行读写操作前,我们需要先进行以下两个操作:

1、实例化ConfigParser对象:

#  实例化configParser对象
cf = configparser.ConfigParser()

2、读取配置文件

#  读取config.ini文件
cf.read(config.ini)

然后进行配置文件的读取操作。

以get为例,示例代码如下:

#  定义方法,获取config分组下指定name的值
def getConfigValue(self, name):
value = self.cf.get("config", name)
return value
# 定义方法,获取cmd分组下指定name的值
def getCmdValue(self, name):
value = self.cf.get("cmd", name)
return value

通过get(section, option)方法,可以获取指定分组下指定名称的值,其他方法类似,可参照着尝试。

基本的写入操作:

  • -write(fp)  将config对象写入至某个 .init 格式的文件  Write an .ini-format representation of the configuration state.
  • -add_section(section)   添加一个新的section
  • -set( section, option, value   对section中的option进行设置,需要调用write将内容写入配置文件
  • -remove_section(section)  删除某个 section
  • -remove_option(section, option) 

以set(section, option, value)为例,示例代码如下:

#  定义方法,修改config分组下指定name的值value
def setConfigValue(self, name, value):
cfg = self.cf.set("config", name, value)
fp = open(r'config.ini', 'w')
cfg.write(fp)

其他方法可以自行尝试。

配置文件中的名字是不区分大小写的,如下两个是等价的:

#  不区分大小写,以下两个等价,都获取appActivity的值
self.cf.get("config", "appActivity")
self.cf.get("config", "APPACTIVITY")

在解析时,getboolean()方法查找任何可行的值,例如以下几个都是等价的:

#  以下取得的值都是等价的为ture
[log]
log_error=true
log_error=TRUE
log_error=1
log_error=yes

实例代码1:

config.conf

[section1]
name = test
func = mainhost [section2]
ip = 192.168.2.170

demo.py

import configparser

conf = configparser.ConfigParser()
conf.read("./config.conf") # 获取指定的section, 指定的option的值
name = conf.get("section1", "name")
print(name)
func = conf.get("section1", "func")
print(func) # 获取所有的section
sections = conf.sections()
print(sections) # 写配置文件
# 更新指定section, option的值
conf.set("section2", "port", "") # 写入指定section, 增加新option的值
conf.set("section2", "IEPort", "") # 添加新的 section
conf.add_section("new_section")
conf.set("new_section", "new_option", "https://github.com/Ranxf/") # 写回配置文件
conf.write(open("./config.conf", "w"))

实例代码2:

config.conf

[section1]
name = test
func = mainhost [section2]
ip = 10.1.1.61
port = 8080

demo2.py(读取配置文件)

'''
Date:2017.12.26
Author:Ranxf
''' import configparser conf = configparser.ConfigParser()
conf.read("./config.conf") # 获取指定的section, 指定的option的值
name = conf.get("section1", "name")
print(name)
func = conf.get("section1", "func")
print(func) # 获取所有的section
sections = conf.sections()
print(sections)

demo3.py(写入配置文件):

'''
Date:2017.12.26
Author:Ranxf
''' import configparser conf = configparser.ConfigParser()
conf.read('config.conf') conf.set("section1", "name", "ranxf") # 修改指定section 的option
conf.set("section1", "age", "") # 增加指定section 的option
conf.add_section("section3") # 增加section
conf.set("section3", "site", "hehe.net") # 给新增的section 写入option
conf.write(open('config.conf', 'w'))

写入后的配置文件

 [section1]

name = interfacetest
func = mainhost
age = 21 [section2]
ip = 10.1.1.61
port = 8080 [section3]
site = hehe.net

参考:

https://docs.python.org/3/library/configparser.html

python3_configparser模块详解的更多相关文章

  1. Python中操作mysql的pymysql模块详解

    Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...

  2. python之OS模块详解

    python之OS模块详解 ^_^,步入第二个模块世界----->OS 常见函数列表 os.sep:取代操作系统特定的路径分隔符 os.name:指示你正在使用的工作平台.比如对于Windows ...

  3. python之sys模块详解

    python之sys模块详解 sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和我一起走进python的模块吧! sys模块的常见函数列表 sys.argv: 实现从程序外部向程序传 ...

  4. python中threading模块详解(一)

    python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...

  5. python time 模块详解

    Python中time模块详解 发表于2011年5月5日 12:58 a.m.    位于分类我爱Python 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括: ...

  6. python time模块详解

    python time模块详解 转自:http://blog.csdn.net/kiki113/article/details/4033017 python 的内嵌time模板翻译及说明  一.简介 ...

  7. 小白的Python之路 day5 time,datatime模块详解

    一.模块的分类 可以分成三大类: 1.标准库 2.开源模块 3.自定义模块 二.标准库模块详解 1.time与datetime 在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时 ...

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

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

  9. Python中time模块详解

    Python中time模块详解 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time模块. ...

随机推荐

  1. mysql5.5的安装配置

    1.wget http://120.52.72.23/cdn.mysql.com/c3pr90ntc0td//Downloads/MySQL-5.5/mysql-5.5.50-linux2.6-x86 ...

  2. PagerAdapter 普通写法

    1,viewPagre的普通写法 public ImagePagerAdapter(Context context, List<Photo> imgList) { this.mContex ...

  3. 【黑金原创教程】【TimeQuest】【第六章】物理时钟与外部模型

    声明:本文为黑金动力社区(http://www.heijin.org)原创教程,如需转载请注明出处,谢谢! 黑金动力社区2013年原创教程连载计划: http://www.cnblogs.com/al ...

  4. 利用CSS3制作淡入淡出动画效果

    CSS3新增动画属性“@-webkit-keyframes”,从字面就可以看出其含义——关键帧,这与Flash中的含义一致. 利用CSS3制作动画效果其原理与Flash一样,我们需要定义关键帧处的状态 ...

  5. 170317、到底什么时候该使用MQ?

    一.缘起 一切脱离业务的架构设计与新技术引入都是耍流氓. 引入一个技术之前,首先应该解答的问题是,这个技术解决什么问题. 就像微服务分层架构之前,应该首先回答,为什么要引入微服务,微服务究竟解决什么问 ...

  6. Code Forces 644A Parliament of Berland

    A. Parliament of Berland time limit per test1 second memory limit per test256 megabytes inputstandar ...

  7. 【Python之路】Python目录

    Python基础1 -- Python由来.Python种类.编码方式, Python基础2 -- Python运算符.数据类型.enumerate.range.for循环 python基础3 -- ...

  8. Jenkins 持续集成配置

    Jenkins搭建.NET自动编译测试与发布环境 Jenkins之Deploy部署(包括站点和类库项目) * 续篇--TFS+MSbuild+jenkins 实现 持续集成+自动部署到WEB网站 Je ...

  9. python学习笔记(四)— 函数

    一.函数是什么? 函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的,编程中的函数在英文中也有很多不同的叫法.在BASIC中叫做subroutine(子过程或子程序),在Pasc ...

  10. d3.js:数据可视化利器之 交互行为:响应DOM事件

    selection.on:事件监听操作符 on()操作符可以添加或移除选择集中每个 DOM元素的事件监听函数: selection.on(type[,listener[,capture]]) 参数ty ...