zoukankan      html  css  js  c++  java
  • day22 Python configparser模块

    # 将配置信息写入文件
    
    import configparser
    
    config = configparser.ConfigParser()
    
    config['default'] = {
        "version": "v1.124",
        "session_timeout": 60,
        "keepalived": 120,
    }
    
    config['test-db1'] = {
        "host": "192.168.1.1",
        "port": 1916,
        "username": "root",
        "password": "123456"
    
    }
    
    config['test-db2'] = {
        "host": "192.168.1.2",
        "port": 1916,
        "username": "root",
        "password": "123456"
    
    }
    
    config['test-db3'] = {
        "host": "192.168.1.3",
        "port": 1916,
        "username": "root",
        "password": "123456"
    
    }
    
    f = open("db.config",mode="w",encoding="utf-8")
    
    config.write(f)
    f.flush()
    f.close()
    
    
    
    # 从配置文件中读取信息
    
    import configparser
    
    config = configparser.ConfigParser()
    
    config.read("db.config")
    
    print(config.sections()) # 获取所有的章节 ['default', 'test-db1', 'test-db2', 'test-db3']
    
    print(config.get("default",'keepalived')) # 120 获取章节中的属性,默认所有章节都会继承default
    
    print(config['test-db1']['host']) # 192.168.1.1
    
    for k,v in config['test-db1'].items(): # 遍历章节
        print(k,v)
        
        
    # 增加,删除操作
    
    config.set("test-db1","host","1.1.1.1") # 临时修改,写入文件才能生效
    print(config['test-db1']['host']) # 1.1.1.1
    
    # config.remove_section("test-db3") # 删除章节
    # print(config['test-db3']) # KeyError: 'test-db3'
    
    config.remove_option("test-db3","host") # 删除属性
    for k,v in config['test-db3'].items(): # 遍历章节
        print(k,v)
    
    config.write(open("db.config",mode="w",encoding="utf-8")) # 写回配置文件
    

      

  • 相关阅读:
    [字符串] 洛谷 P2264 情书
    [IDA*] 洛谷 P2324 骑士精神
    [Tarjan] 洛谷 P2746 校园网
    [dp][瞎搞] 洛谷 P2501 数字序列
    [虚树][lca][dfs] 洛谷 P3233 世界树
    [斜率优化][dp] 洛谷 P3648 序列分割
    [带修莫队] Bzoj 2120 数颜色
    [数学][组合数] Jzoj P4257 着色
    [贪心][前缀和] Jzoj P4256 平均数
    [dfs] 洛谷 P2535 收集资源
  • 原文地址:https://www.cnblogs.com/fanghongbo/p/10003937.html
Copyright © 2011-2022 走看看