zoukankan      html  css  js  c++  java
  • configparser的用法

    这是一个简单的配置文件

    [SectionOne]
    Status: Single
    Name: Derek
    Value: Yes
    Age: 30
    Single: True
    
    [SectionTwo]
    FavoriteColor = Green
    [SectionThree]
    FamilyName: Johnson
    
    [Others]
    Route: 66
    解析如下
    >>> import ConfigParser
    >>> Config = ConfigParser.ConfigParser()
    >>> Config
    <ConfigParser.ConfigParser instance at 0x00BA9B20>
    >>> Config.read("c:\tomorrow.ini")
    ['c:\tomorrow.ini']
    >>> Config.sections()
    ['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
    >>>

    程序

    def ConfigSectionMap(section):
        dict1 = {}
        options = Config.options(section)
        for option in options:
            try:
                dict1[option] = Config.get(section, option)
                if dict1[option] == -1:
                    DebugPrint("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict1[option] = None
        return dict1

    读取

    >>> Name = ConfigSectionMap("SectionOne")['name']
    >>> Age = ConfigSectionMap("SectionOne")['age']
    >>> print "Hello %s. You are %s years old." % (Name, Age)
    Hello Derek. You are 30 years old.

    要读布尔变量

    >>> single = Config.getboolean("SectionOne", "single")
    >>> single
    True

    写配置文件

    # lets create that config file for next time...
    cfgfile = open("c:\next.ini",'w')
    
    # add the settings to the structure of the file, and lets write it out...
    Config.add_section('Person')
    Config.set('Person','HasEyes',True)
    Config.set('Person','Age', 50)
    Config.write(cfgfile)
    cfgfile.close()

    读取可变值

    [SectionOne]
    Param1: Hello
    Param2: World
    
    [SectionTwo]
    Param1: ${SectionOne:Param1} ${SectionOne:Param2}
    
    [SectionThree]
    Alpha: One
    Bravo: Two
    Charlie: ${Alpha} Mississippi
    
    >>> import configparser
    >>> settings = configparser.ConfigParser()
    >>> settings._interpolation = configparser.ExtendedInterpolation()
    >>> settings.read('settings.ini')
    ['settings.ini']
    >>> settings.sections()
    ['SectionOne', 'SectionTwo', 'SectionThree']
    >>> settings.get('SectionTwo', 'Param1')
    'Hello World'
    >>> settings.get('SectionThree', 'Charlie')
    'One Mississippi'
  • 相关阅读:
    java支持跨平台获取cpuid、主板id、硬盘id、mac地址 (兼容windows、Linux)
    Oracle 数据导入导出
    Linux下通过脚本自动备份Oracle数据库并删除指定天数前的备份
    Liunx下查看服务器硬件信息
    Linux文件类型及如何查看,修改文件读写权限
    Linux ext3 ext4 区别
    网站访问量大 怎样优化mysql数据库
    LeetCode——Coin Change
    LeetCode——two sum
    LeetCode——Edit Distance
  • 原文地址:https://www.cnblogs.com/ppcorn/p/7150470.html
Copyright © 2011-2022 走看看