zoukankan      html  css  js  c++  java
  • python模块之configparser

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

    解析下面的文件格式:

    [DEFAULT]
    ServerAliveInterval = 45   
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
    
    [bitbucket.org]
    User = hg
    
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no

    解析配置文件

    import configparser
    
    conf = configparser.ConfigParser()  # 实例化(生成对象)
    
    # print(conf.sections()) #调用sections方法  []
    
    conf.read('conf.ini')  # 读配置文件(注意文件路径)
    
    print(conf.sections())  # 调用sections方法(默认不会读取default  #['bitbucket.org', 'topsecret.server.com']
    print(conf.default_section)  # ['bitbucket.org', 'topsecret.server.com']
    
    # print(conf['bitbucket.org']['User']) # hg
    
    for key, value in conf['bitbucket.org'].items():
        print(key, value)  # 每个节点会有默认有DEFAULT的参数
    '''
    user hg
    serveraliveinterval 45
    compression yes
    compressionlevel 9
    forwardx11 yes
    '''
    
    if 'user' in conf['bitbucket.org']:
        print('True')

    增删改查
    #
    
    conf = configparser.ConfigParser()
    
    conf.read('conf2.ini')
    #
    print(conf.options('group1'))  # 拿到key
    print(conf['group1']['k2'])  # v2 拿到value
    
    print(conf.has_option('group1', 'key1'))  # False
    
    #
    
    conf.add_section('group3')
    conf['group3']['name'] = 'Alex Li'
    conf['group3']['age'] = '22'
    conf.write(open('conf3.ini', 'w'))
    
    '''
    [group1]
    k1 = v1
    k2 = v2
    
    [group2]
    k1 = v1
    
    [group3]
    name = Alex Li
    age = 22
    '''
    
    #
    
    
    conf.remove_option('group1', 'k2')
    conf.remove_section('group1')  # 把整个group1和里面的内容全删了
    conf.write(open('conf4.ini', 'w'))
    
    #
    
    conf['group1']['k1'] = 'haha'
    conf.write(open('conf2.ini', 'w'))
    给Default增加值的话直接加,不用sections,用sections会报错,sections不会读取default 
    conf['DEFAULT']['character-set-server'] = 'utf-8'
    conf.write(open('co f2.ini', 'w'))

  • 相关阅读:
    iOS-Foundation框架—结构体(转载)
    Spring-boot-admin功能说明
    http状态响应码对照表
    spring cloud config 详解
    bat 常用命令
    kafka 安装
    Zookeeper 安装和配置
    使用事件和消息队列实现分布式事务(转)
    消息总线
    分布式配置中心高可用
  • 原文地址:https://www.cnblogs.com/lshedward/p/10005708.html
Copyright © 2011-2022 走看看