python3-configparser使用例程

实例

例1 写配置文件:

import configparser

config = configparser.RawConfigParser()

# When adding sections or items, add them in the reverse order of
# how you want them to be displayed in the actual file.
# In addition, please note that using RawConfigParser's and the raw
# mode of ConfigParser's respective set functions, you can assign
# non-string values to keys internally, but will receive an error
# when attempting to write to a file or when you get it in non-raw
# mode. SafeConfigParser does not allow such assignments to take place.
session = "Section1"
config.add_section(session)
config.set(session, 'an_int', '15')
config.set(session, 'a_bool', 'true')
config.set(session, 'a_float', '3.1415')
config.set(session, 'baz', 'fun')
config.set(session, 'bar', 'Python')
config.set(session, 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
    config.write(configfile)

例2 读配置文件:

import configparser

config = configparser.RawConfigParser()
config.read('example.cfg')

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print("a_float:", a_float)
print("an_int:", an_int)

# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
    print("foo:", config.get('Section1', 'foo'))

例3 读取插入值:

import configparser

config = configparser.ConfigParser()
config.read('example.cfg')

# Set the third, optional argument of get to 1 if you wish to use raw mode.
print(config.get('Section1', 'foo', raw=False))
print(config.get('Section1', 'foo', raw=True))

# The optional fourth argument is a dict with members that will take
# precedence in interpolation.
print(config.get('Section1', 'foo', raw=False, vars={'bar': 'Documentation',
                                        'baz': 'evil'}))

例4 默认值:

import configparser

# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')

print(config.get('Section1', 'foo'))  # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo'))  # -> "Life is hard!"

例5 在各Session之间移动选项:

import configparser


def opt_move(config, section1, section2, option):
    try:
        config.set(section2, option, config.get(section1, option, raw=True))
    except configparser.NoSectionError:
        # Create non-existent section
        config.add_section(section2)
        opt_move(config, section1, section2, option)
    else:
        config.remove_option(section1, option)
        
config = configparser.ConfigParser()
config.read('example.cfg')
opt_move(config, "Section1", "Section2", "foo")
#config.write("example.cfg")
with open('example.cfg', 'w') as configfile:
    config.write(configfile)

例6 配置文件中有空值:

import configparser
import io

sample_config = """
    [mysqld]
    user = mysql
    pid-file = /var/run/mysqld/mysqld.pid
    skip-external-locking
    old_passwords = 1
    skip-bdb
    skip-innodb
    """

config = configparser.RawConfigParser(allow_no_value=True)
config.read_file(io.StringIO(sample_config))

# Settings with values are treated as before:
print(config.get("mysqld", "user"))

# Settings without values provide None:
print(config.get("mysqld", "skip-bdb"))

# Settings which aren't specified still raise an error:
print(config.get("mysqld", "does-not-exist"))

参考:http://blog.csdn.net/miner_k/article/details/77857292







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值