configparser的用法

本文介绍了使用Python的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'

 

转载于:https://www.cnblogs.com/ppcorn/p/7150470.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值