Python—11.1、Ini文件解析

在程序设计中,配置文件是重要的组成部分,提供了通过外部配置控制程序运行逻辑的入口;

1、ini 文件

.ini 文件是Initialization File的缩写,即初始化文件,是windows的系统配置文件所采用的存储格式。.ini配置文件的后缀或扩展名也可以是 ~.conf ~.cfg ~.txt 等。

1.1、配置规范

结构:.ini 文件的由 通常由节(Section)、键(key)和值(value)组成;
注释:.ini 文件的注释 以符号 ;或者 #开头,其后面内容为注释部分;

;这是一个注释的示例-A
#这是一个注释的示例-B
[section_A]
  • 完整配置
    文件 dbEnvconf.ini内容如下:
;这是一个注释的示例-A
#这是一个注释的示例-B
[mysql_A]
host = 77.77.77.77
port = 5432
dbname = dbsid
user = username
passwd = password

[oracle_B]
host = 99.99.99.99
port = 1521
dbname = dbsid
user = username
passwd = password

1.2、configparser库

以下为 configparser库 源码中关于常用方法的说明;

"""Configuration file parser.

A configuration file consists of sections, lead by a "[section]" header,
and followed by "name: value" entries, with continuations and such in
the style of RFC 822.

Intrinsic defaults can be specified by passing them into the
ConfigParser constructor as a dictionary.

class:

ConfigParser -- responsible for parsing a list of
                    configuration files, and managing the parsed database.

    methods:

    __init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
             delimiters=('=', ':'), comment_prefixes=('#', ';'),
             inline_comment_prefixes=None, strict=True,
             empty_lines_in_values=True, default_section='DEFAULT',
             interpolation=<unset>, converters=<unset>):
        Create the parser. When `defaults' is given, it is initialized into the
        dictionary or intrinsic defaults. The keys must be strings, the values
        must be appropriate for %()s string interpolation.

        When `dict_type' is given, it will be used to create the dictionary
        objects for the list of sections, for the options within a section, and
        for the default values.

        When `delimiters' is given, it will be used as the set of substrings
        that divide keys from values.

        When `comment_prefixes' is given, it will be used as the set of
        substrings that prefix comments in empty lines. Comments can be
        indented.

        When `inline_comment_prefixes' is given, it will be used as the set of
        substrings that prefix comments in non-empty lines.

        When `strict` is True, the parser won't allow for any section or option
        duplicates while reading from a single source (file, string or
        dictionary). Default is True.

        When `empty_lines_in_values' is False (default: True), each empty line
        marks the end of an option. Otherwise, internal empty lines of
        a multiline option are kept as part of the value.

        When `allow_no_value' is True (default: False), options without
        values are accepted; the value presented for these is None.

        When `default_section' is given, the name of the special section is
        named accordingly. By default it is called ``"DEFAULT"`` but this can
        be customized to point to any other valid section name. Its current
        value can be retrieved using the ``parser_instance.default_section``
        attribute and may be modified at runtime.

        When `interpolation` is given, it should be an Interpolation subclass
        instance. It will be used as the handler for option value
        pre-processing when using getters. RawConfigParser object s don't do
        any sort of interpolation, whereas ConfigParser uses an instance of
        BasicInterpolation. The library also provides a ``zc.buildbot``
        inspired ExtendedInterpolation implementation.

        When `converters` is given, it should be a dictionary where each key
        represents the name of a type converter and each value is a callable
        implementing the conversion from string to the desired datatype. Every
        converter gets its corresponding get*() method on the parser object and
        section proxies.

    sections()
        Return all the configuration section names, sans DEFAULT.

    has_section(section)
        Return whether the given section exists.

    has_option(section, option)
        Return whether the given option exists in the given section.

    options(section)
        Return list of configuration options for the named section.

    read(filenames, encoding=None)
        Read and parse the iterable of named configuration files, given by
        name.  A single filename is also allowed.  Non-existing files
        are ignored.  Return list of successfully read files.

    read_file(f, filename=None)
        Read and parse one configuration file, given as a file object.
        The filename defaults to f.name; it is only used in error
        messages (if f has no `name' attribute, the string `<???>' is used).

    read_string(string)
        Read configuration from a given string.

    read_dict(dictionary)
        Read configuration from a dictionary. Keys are section names,
        values are dictionaries with keys and values that should be present
        in the section. If the used dictionary type preserves order, sections
        and their keys will be added in order. Values are automatically
        converted to strings.

    get(section, option, raw=False, vars=None, fallback=_UNSET)
        Return a string value for the named option.  All % interpolations are
        expanded in the return values, based on the defaults passed into the
        constructor and the DEFAULT section.  Additional substitutions may be
        provided using the `vars' argument, which must be a dictionary whose
        contents override any pre-existing defaults. If `option' is a key in
        `vars', the value from `vars' is used.

    getint(section, options, raw=False, vars=None, fallback=_UNSET)
        Like get(), but convert value to an integer.

    getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
        Like get(), but convert value to a float.

    getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
        Like get(), but convert value to a boolean (currently case
        insensitively defined as 0, false, no, off for False, and 1, true,
        yes, on for True).  Returns False or True.

    items(section=_UNSET, raw=False, vars=None)
        If section is given, return a list of tuples with (name, value) for
        each option in the section. Otherwise, return a list of tuples with
        (section_name, section_proxy) for each section, including DEFAULTSECT.

    remove_section(section)
        Remove the given file section and all its options.

    remove_option(section, option)
        Remove the given option from the given section.

    set(section, option, value)
        Set the given option.

    write(fp, space_around_delimiters=True)
        Write the configuration state in .ini format. If
        `space_around_delimiters' is True (the default), delimiters
        between keys and values are surrounded by spaces.
"""

1.3、参数解析

python 内置的 configparser 标准库进行 .ini 文件的解析;

  • 代码实现
# coding=utf-8
"""
@DevTool  : PyCharm
@Author   : gzh
@DateTime : 2022/5/7 14:02
@FileName : readIniFile.py
"""

import configparser

configParser = configparser.ConfigParser()
iniFile = "dbEnvConf.ini"
configParser.read(iniFile, encoding="utf-8")

# 返回 List
list_mysql_A = configParser.items("mysql_A")
print(list_mysql_A)
# 返回 dict
dict_mysql_A = dict(configParser.items("mysql_A"))
print(dict_mysql_A)

输出结果

D:\SoftWare\Python\python.exe E:/PythonProject/FileOperTest/readIniFile.py
[('host', '77.77.77.77'), ('port', '5432'), ('dbname', 'dbsid'), ('user', 'username'), ('passwd', 'password')]
{'host': '77.77.77.77', 'port': '5432', 'dbname': 'dbsid', 'user': 'username', 'passwd': 'password'}

Process finished with exit code 0
  • 通过 configParser.sections()可以获取配置文件的所有 section名称,不包含 key-value内容;
  • 通过 configParser.items("section")获取整个 section的参数内容,返回 list 类型;
  • 通过 configParser["section"]["key"]获取指定section下特定 key的 value;
  • 通过 configParser.get("section", "key")获取指定section下特定 key的 value;

代码实现

sections = configParser.sections()
print("configParser.sections()-->",sections)
host_B = configParser["oracle_B"]["host"]
print('configParser["oracle_B"]["host"]-->',host_B)
port_B = configParser.get("oracle_B","port")
print('configParser.get("oracle_B","port")-->',port_B)

输出结果

D:\SoftWare\Python\python.exe E:/PythonProject/FileOperTest/readIniFile.py
configParser.sections()--> ['mysql_A', 'oracle_B']
configParser["oracle_B"]["host"]--> 99.99.99.99
configParser.get("oracle_B","port")--> 1521

Process finished with exit code 0

1.4、配置写入

此部分自行按照源码说明验证;

========================================= over ========================================

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值