python配置文件的使用

发布时间:2019-07-08 18:00:57编辑:auto阅读(2231)

    本文转载自:https://www.cnblogs.com/cnhkzyy/p/9294829.html

    一. 什么是配置文件?为什么要做配置文件?

    将所有的代码和配置都变成模块化可配置化,这样就提高了代码的重用性,不再每次都去修改代码内部,这个就是我们逐步要做的事情,可配置化

     

    二. python中的ConfigParser类

    模块:from configparser import ConfigParser

     

    configparser是Python自带的模块,用法如下:

    1. 创建ConfigParser对象。并调用read()函数打开配置文件,里面填的参数是地址

    2. 配置文件的格式是:[]包含的叫section,section下有option=value这样的键值

    3. 常用配置函数如下

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

    options(section)  得到该section的所有option (key值)

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

    get(section, option)  得到section中option的值,返回为string类型,指定标签下面的key对应的value值

    getint(section, option)  得到section中的option值,返回为int类型

     

    add_section()  往配置文件中添加section

    set(section, name, value)  在section下设置name=value

    with open(configfile) as cfile:

      write(cfile)

    将新增的配置信息写入到文件中

     

    三. 实例

    1. 在lesson_config包下创建一个配置文件db.cfg和一个py文件config_operate.py

    2. db.cfg的内容为

    复制代码

    [mysql_db_test]
    host=localhost
    port=3306
    db=mysql
    user=root
    passwd=123456

    复制代码

    3. config_operate.py的内容为

    from configparser import ConfigParser

    #初始化类 

    cp = ConfigParser() 

    cp.read("db.cfg") 

    #得到所有的section,以列表的形式返回 

    section = cp.sections()[0] 

    print(section) 

    #得到该section的所有option 

    print(cp.options(section)) 

    #得到该section的所有键值对 

    print(cp.items(section)) 

    #得到该section中的option的值,返回为string类型 

    print(cp.get(section, "db")) 

    #得到该section中的option的值,返回为int类型 

    print(cp.getint(section, "port"))


    运行结果

    mysql_db_test
    ['host', 'port', 'db', 'user', 'passwd']
    [('host', 'localhost'), ('port', '3306'), ('db', 'mysql'), ('user', 'root'), ('passwd', '123456')]
    mysql
    3306


关键字

上一篇: python 循环

下一篇: Python正则表达式 re(regul