python3-configparser使用例程
发布日期:2021-07-22 21:24:45 浏览次数:2 分类:技术文章

本文共 3563 字,大约阅读时间需要 11 分钟。

实例

例1 写配置文件:

import configparserconfig = 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 configparserconfig = 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 typesa_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 configparserconfig = 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' eachconfig = 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 configparserdef 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 configparserimport iosample_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"))

参考:

转载地址:https://blog.csdn.net/menghaocheng/article/details/79525429 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:从命令行创建github仓库
下一篇:程序员.自嘲

发表评论

最新留言

很好
[***.229.124.182]2024年04月16日 01时43分43秒