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")) # 写回配置文件
    

      

  • 相关阅读:
    Web Site Administration Tool 文章收集
    Sql中补零方法及其它
    PowerDesigner 教程
    什么是Zend
    什么是CMS系统?
    谈谈今天遇到的编译工具查错的问题
    Lec4快速排序
    堆排序 zz
    强大的Python
    Lec6待学习的堆排序
  • 原文地址:https://www.cnblogs.com/fanghongbo/p/10003937.html
Copyright © 2011-2022 走看看