zoukankan      html  css  js  c++  java
  • python中配置文件的使用

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

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

    二. 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
  • 相关阅读:
    hdu 2485 Destroying the bus stations 迭代加深搜索
    hdu 2487 Ugly Windows 模拟
    hdu 2492 Ping pong 线段树
    hdu 1059 Dividing 多重背包
    hdu 3315 My Brute 费用流,费用最小且代价最小
    第四天 下载网络图片显示
    第三天 单元测试和数据库操作
    第二天 布局文件
    第一天 安卓简介
    Android 获取存储空间
  • 原文地址:https://www.cnblogs.com/my_captain/p/9294829.html
Copyright © 2011-2022 走看看