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

      

  • 相关阅读:
    释放 Linux 系统预留的硬盘空间(转)
    内存置换空间(swap)之建置(转)
    启动挂载(转)
    硬链接与软链接(转)
    磁盘与目录的容量(转)
    linux网络相关配置文件(转)
    python资源库大全
    pikachu学习记录(二)
    pikachu学习记录(一)
    sqlmap基础用法
  • 原文地址:https://www.cnblogs.com/fanghongbo/p/10003937.html
Copyright © 2011-2022 走看看