zoukankan      html  css  js  c++  java
  • Python之配置文件读写

    ConfigParser模块
    一、创建配置文件
    在D盘建立一个配置文件,名字为:test.ini
    内容如下:
    [baseconf]
    host=127.0.0.1
    port=3306
    user=root
    password=root
    db_name=gloryroad
    [test]
    ip=127.0.0.1
    int=1
    float=1.5
    bool=True
    注意:要将文件保存为ansi编码,utf-8编码会报错
    文件中的[baseconf]为section
     
    二、读配置文件
    import ConfigParser
    cf=ConfigParser.ConfigParser()
    cf.read(path) 读配置文件(ini、conf)返回结果是列表
    cf.sections() 获取读到的所有sections(域),返回列表类型
    cf.options('sectionname') 某个域下的所有key,返回列表类型
    cf.items('sectionname') 某个域下的所有key,value对
    value=cf.get('sectionname','key') 获取某个yu下的key对应的value值
    cf.type(value) 获取的value值的类型
     
    (1)getint(section, option)
    获取section中option的值,返回int类型数据,所以该函数只能读取int类型的值。
    (2)getboolean(section, option)
    获取section中option的值,返回布尔类型数据,所以该函数只能读取boolean类型的值。
    (3)getfloat(section, option)
    获取section中option的值,返回浮点类型数据,所以该函数只能读取浮点类型的值。
    (4)has_option(section, option)
    检测指定section下是否存在指定的option,如果存在返回True,否则返回False。
    (5)has_section(section)
    检测配置文件中是否存在指定的section,如果存在返回True,否则返回False。
     
    三、动态写配置文件
    cf.add_section('test') 添加一个域
    cf.set('test3','key12','value12') 域下添加一个key value对
    cf.write(open(path,'w')) 要使用'w'
  • 相关阅读:
    @@@并发实战
    @@@jvm实战
    @@@spring Boot环境下dubbo+zookeeper实战
    FastJson 支持配置的PropertyNamingStrategy四种策略
    利用MySQL统计一列中不同值的数量方法示例
    Springboot+websocket+定时器实现消息推送
    Spring AOP中args()、arg-names、argNames
    squid,nginx,lighttpd反向代理的区别
    HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
    HTTP 错误 500.24
  • 原文地址:https://www.cnblogs.com/emily-qin/p/8022292.html
Copyright © 2011-2022 走看看