python-ConfigParser模块

ConfigParser模块在python中是用来读取配置文件,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用再程序中硬编码,可以是你的程序变得灵活起来。

注意:在python 3 中ConfigParser模块名已更名为configparser

函数

读取配置文件

read(filename) 直接读取ini文件内容
sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option
items(section) 得到该section的所有键值对
get(section,option) 得到section中option的值,返回为string类型
getint(section,option) 得到section中option的值,返回为int类型
getfloat(section,option)得到section中option的值,返回为float类型
getboolean(section, option)得到section中option的值,返回为boolean类型

 

写入配置文件

add_section(section) 添加一个新的section
has_section(section) 判断是否有section
set( section, option, value) 对section中的option进行设置
remove_setion(section)删除一个section
remove_option(section, option)删除section中的option
write(fileobject)将内容写入配置文件

使用:

配置文件的格式如下:中括号“[]”内包含的为:section, section下面为类似于key-value的键值对的option的内容

#config.ini

[private_debug] # debug测试服务器 tester = Test environment = debug versionCode = 5.0.0 host = http://gz.test.com:810 loginHost = fronted-docker-pre2/postLogin [online_release] #release 正式服务 tester = xiao xi environment = release versionCode = 5.0.0 versionCode = v1.0 host = http://gz.live.com loginHost = frontend-docker-pre2/postLogin

ConfigParser 初始化对象

from configparser import ConfigParser
config = ConfigParser()
#读取ini配置文件内容
config.read(config.ini, encoding="utf-8")

常用方法

1.获取所有的section节点


from configparser import ConfigParser
config = ConfigParser()
#读取ini配置文件内容
config.read(config.ini, encoding="utf-8")
#获取section sec = config.sections() print(sec) #运行结果 ['private_debug', 'online_release']

2.获取section的options,即key值

from configparser import ConfigParser
config = ConfigParser()
#读取ini配置文件内容
config.read(config.ini, encoding="utf-8") opt_key = config.options("private_debug") print(opt_key) #运行结果: ['tester', 'environment', 'versioncode', 'host', 'loginhost']

 3.获取section下的option值(键值对)

from configparser import ConfigParser
config = ConfigParser()
#读取ini配置文件内容
config.read(config.ini, encoding="utf-8")
r = config.get(‘private_debug’,‘tester')

#运行结果:
test

 

 

 

参考文献:

https://www.cnblogs.com/ming5218/p/7965973.html

https://blog.csdn.net/henulwj/article/details/49174355?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control&dist_request_id=1328627.8853.16153468533666025&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control

 

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...