zoukankan      html  css  js  c++  java
  • python configparser()配置文件

    一、ConfigParser简介

    ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。

     1 [DEFAULT]
     2 severallvelimterval = 45
     3 compression = yes
     4 compressionlevel = 9
     5 forwardx11 = yes
     6 
     7 [bitbacket.org]
     8 user = hg
     9 
    10 [topsecret.server.com]
    11 port  = 50022
    12 forwar0x11 = no

      生成配置文件:

    import configparser
    
    config = configparser.ConfigParser()
    
    config["DEFAULT"] = {
                       'SeverAllvelImterval': '45',
                       'Compression' : 'yes',
                        'CompressionLevel' : '9',
                         'ForwardX11': 'yes'}
    config["bitbacket.org"] = {'User':'hg'}
    config["topsecret.server.com"] = {'Port ':'50022',
                                          'Forwar0x11':'no'  }
    with open('example.ini','w') as configfile:
         config.write(configfile)

    二、ConfigParser 常用方法

    1. 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中:

     

    config.read("example.ini")
    print(config.sections())

     

    将输出:

    ['bitbacket.org', 'topsecret.server.com']

    备注:“DEFAULT”section默认不显示

        2. 获取指定section 的options。即将配置文件某个section 内key 读取到列表中:

    config.read("example.ini")
    print(config.options("bitbacket.org"))

    将输出:

    ['user', 'severallvelimterval', 'compression', 'compressionlevel', 'forwardx11']

    备注:“options”会默认输出default模块的options

    3. 获取指定section 的配置信息。

    config.read("example.ini")
    print(config.items("topsecret.server.com"))

    将输出:

    [('severallvelimterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('port ', '50022'), ('forwar0x11', 'no'), ('port', '50022')]

    4. 按照类型读取指定section 的option 信息。

    同样的还有getfloat、getboolean。

    print(config.getint("DEFAULT",'SeverAllvelImterval'))

    将输出:

      45

    5. 设置某个option 的值。(记得最后要写回)

    config.set("DEFAULT",'SeverAllvelImterval', '50')
    config.write(open('example.ini','w'))

    6.添加一个section。(同样要写回)

    config.set("DEFAULT",'ant', '50')
    config.write(open('example.ini','w'))

    7. 移除section 或者option 。(只要进行了修改就要写回的哦)

    config.remove_option("DEFAULT",'ant')
    config.write(open('example.ini','w'))
    
    config.remove_section("DEFAULT")
    config.write(open('example.ini','w'))

     

  • 相关阅读:
    js获取对象的最后一个
    vue UI框架
    从前端和后端两个角度分析jsonp跨域访问(完整实例)
    Ajax跨域访问解决方案
    js中将字符串转换成json的三种方式
    【转载】COM 组件设计与应用(九)——IDispatch 接口 for VC6.0
    【转载】COM 组件设计与应用(八)——实现多接口
    【转载】COM 组件设计与应用(七)——编译、注册、调用
    【转载】COM 组件设计与应用(六)——用 ATL 写第一个组件
    【转载】COM 组件设计与应用(五)——用 ATL 写第一个组件
  • 原文地址:https://www.cnblogs.com/qinyanli/p/8286882.html
Copyright © 2011-2022 走看看