当前位置: 首页>移动开发>正文

玩转 Python 之 Configparser 模块

前言

来啦老铁!

笔者已经有一月有余没有生产文章了,真该打!
今天就简单学个 Python 的模块吧,他就是:

  • Configparser 模块。

本文知识点主要来源于网络上的文章,比较分散就没有放文章链接了~

学习路径

  1. Configparser 模块简介;
  2. Configparser 模块安装;
  3. 使用 Configparser 模块;

1. Configparser 模块简介;

在 python 日常开发工作当中,我们可以用 py 文件、ini、xml、excel、yaml、json、toml 等来管理我们的配置信息,伴随而来的是对这些文件处理的方法,Configparser 模块就是用来处理 ini 文件的模块。

2. Configparser 模块安装;

pip3 install configparser

安装超级快,说明模块很小~

玩转 Python 之 Configparser 模块,第1张
方法

除了一些系统定义的函数和一些常量,也就这么些方法,不多。接下来我们一个一个用用看~

3. 使用 Configparser 模块;

  • 代码演示:
import configparser
import os


def test():
    # 初始化实例并读取配置文件:
    config_parser = configparser.ConfigParser()
    config_parser.read("config.ini", encoding="utf-8")

    print("获取所用 section 节点:", config_parser.sections())
    print("获取指定 section 的 options,即将配置文件中的某个 section 内的所有 key 读取到列表中:", config_parser.options("section1"))
    print("判断配置文件中是否有某个 section:", config_parser.has_section("demo"))
    print("判断某个 section 下是否有某个 option:", config_parser.has_option("section1", "age"))
    print("判断某个 section 下是否有某个 option:", config_parser.has_option("section1", "developer"))

    print("获取指定 section 的指定 option(值是字符串或其他数字类型都可以):", config_parser.get("section1", "name"))
    print("获取指定 section 的指定 option(值是字符串或其他数字类型都可以):", config_parser.get("section1", "age"))
    print("获取指定 section 的指定 option(值是字符串或其他数字类型都可以):", config_parser.get("section2", "name"))
    print("获取指定 section 的指定 option(值必须是整数型数据,否则报错):", config_parser.getint("section1", "age"))
    print("获取指定 section 的指定 option(值必须是浮点型数据,否则报错):", config_parser.getfloat("section1", "weight"))
    print("获取指定 section 的指定 option(值必须是 boolean 值型数据,否则报错):", config_parser.getboolean("section1", "student"))

    # 添加 section 和 option
    config_parser.add_section("section3")
    config_parser.set("section3", "name", "baby")
    config_parser.write(open("config.ini", "w"))
    # 删除 section 和 option
    config_parser.remove_option("section3", "name")
    config_parser.remove_section("section3")
    config_parser.write(open("config.ini", "w"))

    # 高级用法 1:从字典中读取配置
    config_dict = {
        "oracle": {
            "hostname": "127.0.0.1",
            "username": "admin",
            "password": "admin123"
        }
    }
    config_parser.read_dict(config_dict)
    print("从字典中读取配置:", config_parser.get("oracle", "hostname"))

    # 高级用法 2:从字符串中读取配置
    config_str = """
        [section4]
        version = 1.0.1
        author = dylan.zhang
        date = 2023.3.14
    """
    config_parser.read_string(config_str)
    print("从字符串中读取配置:", config_parser.get("section4", "version"))

    # 高级用法 3:从文件对象中读取配置
    with open('config.ini') as config_file:
        config_parser.read_file(config_file)
        print("从文件对象中读取配置:", config_parser.get("section1", "height"))
        config_file.close()

    # 高级用法 4:读取 section 并返回可迭代的列表
    config_items = config_parser.items("section1")
    for key, value in config_items:
        print("迭代读取 section1 配置:", key, value)
    for index, value in enumerate(config_items):
        print("迭代读取 section1 配置:", index, value)


if __name__ == '__main__':
    test()

  • 执行代码演示:
玩转 Python 之 Configparser 模块,第2张
执行代码演示

至此,我们对 Configparser 模块的使用已经基本探索完毕,其接口简单,相对全面,是读取 ini 配置文件的好帮手~

今天就到这吧,能力有限,欢迎指正、互相交流,感谢~

感谢~


https://www.xamrdz.com/mobile/4ek1874913.html

相关文章: