• python 读写配置文件


    import  configparser
    import os
    # 一:读取
    # -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()函数。
    cf=configparser.ConfigParser()
    cf.read(r"E:PyCharmWorkSpaceAutoInterfaceTestconfig	est_config.ini")
    secs=cf.sections()
    print("配置文件所有的section"+str(secs))
    opts=cf.options("db")
    print("section-db下的所有options"+str(opts))
    items=cf.items("db")
    print("section-db下的所有items"+str(items))
    db_host=cf.get("db","db_host")
    print("获取指定section 下option的值"+str(db_host))
    
    # 二:写入
    # -write(fp)  将config对象写入至某个 .init 格式的文件  Write an .ini-format representation of the configuration state.
    # -add_section(section)添加一个新的section
    # -set( section, option, value)   对section中的option进行设置,需要调用write将内容写入配置文件 ConfigParser2
    # -remove_section(section) 删除某个 section
    # -remove_option(section, option) 除某个 section 下的 option
    # ps:需要配合文件读写函数来写入文件
    
    os.chdir("E:PyCharmWorkSpaceAutoInterfaceTestconfig")
    cf1=configparser.ConfigParser()
    cf1.add_section("test")
    cf1.set("test","count","1")
    cf1.add_section("test1")
    cf1.set("test1","name","乐乐")
    cf1.set("test1","age","18")
    cf1.set("test1","english_name","lele")
    with open("test_wconfig.ini","w+") as f:
        cf1.write(f)
  • 相关阅读:
    .net core
    web api对接小程序基本签名认证
    微信小程序主要开发语言
    C# 用Singleton类构建多线程单例模式
    web api与mvc的区别
    sql 简单分页查询(ror_number() over)
    sql查询当前数据库的所有表名
    C# 身份证号码15位和18位验证
    C# 人民币大写金额转换
    编写类-用户类
  • 原文地址:https://www.cnblogs.com/yangjr/p/12936953.html
Copyright © 2020-2023  润新知