前言

使用配置文件可以在不修改程序的情况下,做到对程序功能的定制。Python 使用自带的configParser模块可以很方便的读写配置文件的信息。

configParser

支持的方法

ConfigParser模块支持很多种读取数据的方法,最常用的是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() 函数。

因为是内置模块,所以可以很方便的查看源码,如博主电脑中该模块在D:\Python3\Lib\configparser.py,有兴趣的可以看看源码的实现方式。

下面介绍一些实际使用。

配置文件内容

首先我们新建一个文件,如config.ini,或者config.conf,内容如下

[broswer_name]
broswer = 'firefox'

[server]
server = 'http://www.baidu.com/'

封装

import configparser
import os

class ConfigRead(object):
    @staticmethod
    def get_value():
        # 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 = ConfigRead()
    print(trcf.get_value())

获取文件路径

博主的config文件放在config文件夹中,试过很多方式来获取文件绝对路径,如下方式最佳

  • os.path.abspath(os.path.join('config','config.ini'))

最新文章

  1. Mac OS 后台服务注册
  2. redis API使用说明
  3. 未能加载文件或程序集“System.WEB.DataVisualization, Version=3.5.0.0, Culture=neutral
  4. 浅谈Dynamic 关键字系列之一:dynamic 就是Object(转)
  5. 利用ADO方式连接SQLServer2008出现的问题
  6. zabbix之3触发器/action及模板
  7. HDU--杭电--4502--吉哥系列故事——临时工计划--背包--01背包
  8. Mac使用nginx+rtmp服务器
  9. 找出共同好友 - 数据挖掘 - Scala版
  10. windbg关于.NET分析的扩展命令
  11. Spark源码系列:DataFrame repartition、coalesce 对比
  12. Android学习之AutoCompleteTextView
  13. Tensorflow 方法记录
  14. 线性代数的视角理解LSR(least square regression)的参数评估算法本质
  15. wiremock docker 运行
  16. 利用__attribute__((section()))构建初始化函数表【转】
  17. 使用Java读取配置文件
  18. day-15 用opencv怎么扫描图像,利用查找表和计时
  19. 【bzoj2144】跳跳棋
  20. asp.net mvc 静态化

热门文章

  1. php使用amqplib方式使用rabbitmq
  2. python操作socket
  3. PAT 1033 To Fill or Not to Fill[dp]
  4. Python遇到SyntaxError: Non-ASCII character '\xe5' in file D:\eclipseworkspace\test\test_urllib2.py on line2
  5. django 登陆增加除了用户名之外的手机和邮箱登陆
  6. glib简单记录包括字符串,主循环,回调函数和xml解析
  7. Oracle 性能调优 SQL_TRACE
  8. SQL Server 创建游标(cursor)
  9. smart基础原理
  10. java反射子之获取方法信息(二)