Python模块学习之ConfigParser读写配置信息
2017-07-19 11:16
676 查看
本文记录使用 自动化过程中,学习的使用ConfigParser类读取ini配置文件的方法。
任何一个项目,都会涉及到了配置文件的管理,python 读取配置文件的信息很方便,可以直接使用自带的configParser模块。
因为是内置模块,可以很方便的查看源码,如博主电脑中该模块在“D:\Program Files\Python3\Lib\configparser.py”
os.path.abspath(os.path.join('config','config.ini'))
任何一个项目,都会涉及到了配置文件的管理,python 读取配置文件的信息很方便,可以直接使用自带的configParser模块。
因为是内置模块,可以很方便的查看源码,如博主电脑中该模块在“D:\Program Files\Python3\Lib\configparser.py”
配置文件内容
新建一个文件,如config.ini,或者config.conf,内容如下[broswer_name] broswer = 'firefox' [server] server = 'http://www.baidu.com/'
获取文件路径
博主的config文件放在config文件夹中,百度搜了很多的方式来获取文件绝对路径,如下方式最佳os.path.abspath(os.path.join('config','config.ini'))
支持的方法
config模块支持很多种读取数据的方法,最常用的是get方法,通过section 及 option的值获取对应的数据- 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() 函数。
方法封装
# coding=utf-8 import ConfigParser import os class Config_read(object): def get_value(self): #file_path = os.path.dirname(os.path.realpath(__file__)) + os.path.join(r'\config','config.ini') file_path = os.path.abspath(os.path.join('config','config.ini')) config = ConfigParser.ConfigParser() config.read(file_path) #print file_path browser = config.get("broswer_name", "broswer") #分别代表所在区域名 和变量名 url = config.get("server", "server") return (browser, url) if __name__ == '__main__': trcf = Config_read() print trcf.get_value()
相关文章推荐
- Python模块学习之ConfigParser读写配置信息
- Python模块之ConfigParser - 读写配置文件
- Python - ConfigParser模块读写配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- Python自动化测试 (二) ConfigParser模块读写配置文件
- Python模块之ConfigParser - 读写配置文件
- Python模块之ConfigParser - 读写配置文件
- Python自动化测试 -ConfigParser模块读写配置文件
- Python自动化测试 (二) ConfigParser模块读写配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- ConfigParser模块学习: 用python解析配置文件
- Python模块之ConfigParser - 读写配置文件
- 用ConfigParser模块读写配置文件——Python
- python ConfigParser 模块学习
- Python模块之: ConfigParser 配置文件读取
- python学习之路-7 模块configparser/xml/shutil/subprocess以及面向对象初级入门
- Python 解析配置模块之ConfigParser详解
- Python 解析配置模块之ConfigParser详解
- Python配置文件解析模块ConfigParser使用实例
- Python 解析配置模块之ConfigParser详解