IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> Python开发—Ini文件解析 -> 正文阅读

[Python知识库]Python开发—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 = devdb
user = sjjc_bz
passwd = password

[oracle_B]
host = 99.99.99.99
port = 1521
dbname = devdb
user = sjjc_bz
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.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', 'devdb'), ('user', 'sjjc_bz'), ('passwd', 'password')]
{'host': '77.77.77.77', 'port': '5432', 'dbname': 'devdb', 'user': 'sjjc_bz', '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、配置写入

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

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-05-09 12:36:21  更:2022-05-09 12:38:23 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/27 18:36:21-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码
数据统计