zoukankan      html  css  js  c++  java
  • python入门:常用模块—configparser模块

    此模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

    来看一个好多软件的常见配置文件格式如下

    import configparser
    config = configparser.ConfigParser()  # 实例化(生成对象)
    data = config.read('example.ini')
    print(data)
    
    print(config.sections())    # 调用sections方法(默认不会读取default)
    print('bitbucket.org' in config)        # 判断元素是否在sections列表里
    
    print(config['bitbucket.org']['User'])      # 通过字典的形式取值
    print(config['topsecret.server.com']['Port'])
    
    for key in config['bitbucket.org']:  # for 循环bitucket.org字典的key
        print(key)
    
    config = configparser.ConfigParser()
    config.read('group.ini')
    
    secs = config.sections()
    print(secs)
    options = config.options('group2')  # 获取指定section的keys
    print(options)
    
    items_list = config.items('group2')  # 获取指定 section 的 keys & values ,key value 以元组的形式
    print(items_list)
    va1 = config.get('group1', 'k1')
    print(va1)
    
    sec=config.remove_section('group1')  # 删除section 并返回状态(true, false)
    config.write(open('group.ini', 'w'))
    
    sec = config.has_section('test')
    sec = config.add_section('test')
    config.write(open('group.ini', 'w', encoding= 'utf-8'))
    
    config.set('group2', 'k3', '333')
    config.write(open('group.ini', 'w'))
    
    config.remove_option('group2', 'k1')
    config.write(open('group.ini', 'w'))
    

      



  • 相关阅读:
    观察者模式股票提醒
    中介者模式虚拟聊天室
    模板方法模式数据库的连接
    职责链模式财务审批
    期末总结
    软件需求分析考试
    tomcat启动极其慢的解决方法困扰我一年多的问题终于解决
    状态模式银行账户
    解释器模式
    动态加载JS文件提升访问网站速度
  • 原文地址:https://www.cnblogs.com/mike-liu/p/9085527.html
Copyright © 2011-2022 走看看