python INI文件操作与configparser内置库

目录

INI文件

configparser内置库

类与方法

操作实例

导入INI文件

查询所有节的列表

判断某个节是否存在

查询某个节的所有键的列表

判断节下是否存在某个键

增加节点

删除节点

增加节点的键

修改键值

保存修改结果

获取键值

获取节点所有键值

其他读取方式

从字串中读取 read_string

从字典中读取 read_dict

完整示例代码


INI文件

即Initialization File的缩写,是Windows系统配置文件所采用的存储格式,用于统管Windows的各项配置。虽然Windows 95之后引入了注册表的概念,使得许多参数和初始化信息被存储在注册表中,但在某些场合,INI文件仍然具有其不可替代的地位。

INI文件是一种按照特殊方式排列的文本文件,其格式规范包括节(section)、键(name)和值(value)。节用方括号括起来,单独占一行,用于表示一个段落,区分不同用途的参数区。键(也称为属性)单独占一行,用等号连接键名和键值,例如“name=value”。注释使用英文分号(;)开头,单独占一行,分号后面的文字直到该行结尾都作为注释处理。

INI文件在Windows系统中非常常见,其中最重要的是“System.ini”、“System32.ini”和“Win.ini”等文件。这些文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件来改变应用程序和系统的很多配置。当然,我们自己编写程序时也可以把INI文件作为配置和管理参数的工具,比如python中就有内置库configparser可以方便地配置和管理程序的参数。

configparser内置库

类与方法

    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 objects don't do any sort of interpolation, whereas ConfigParser uses an instance of BasicInterpolation. The library also provides a ``zc.buildout`` 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.

操作实例

就以我电脑上的win.ini的内容作操作对象,为防止乱改windows参数,把win.ini复制到源代码目录中并改名为exam.ini。

; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1

导入INI文件

>>> import configparser
>>> parser = configparser.ConfigParser()
>>> parser.read('exam.ini')
['exam.ini']

可以同时读取多个文件,以文件列表作参数

>>> parser.read(['exam.ini', 'exam1.ini'])
['exam.ini', 'exam1.ini']
>>> parser.read(['exam.ini', 'exam2.ini'])
['exam.ini']
>>> parser.read(['exam2.ini'])
[]

注意:文件不存在并不报错,只是没有对应的返回值。

另一种形式:parser.read_file(file)

>>> with open('exam.ini', 'r') as file:  
...     parser.read_file(file)

主要区别

  • parser.read() 是基于文件名的,它打开文件并读取内容。而 parser.read_file() 则接受一个已经打开的文件对象。
  • parser.read() 可以接受多个文件名,而 parser.read_file() 一次只能处理一个文件对象。
  • 使用 parser.read_file() 时,你需要自己处理文件的打开和关闭。而 parser.read() 则会在内部处理这些操作。
查询所有节的列表

>>> parser.sections()
['fonts', 'extensions', 'mci extensions', 'files', 'Mail']

判断某个节是否存在

>>> parser.has_section('fonts')
True
>>> parser.has_section('font')
False
>>> parser.has_section('files')
True

查询某个节的所有键的列表

>>> parser.options('Mail')
['mapi']
>>> parser.options('mail')
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    parser.options('mail')
  File "D:\Program Files\Python\Lib\configparser.py", line 661, in options
    raise NoSectionError(section) from None
configparser.NoSectionError: No section: 'mail'
>>> parser.options('files')
[]
>>> parser.options('Files')
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    parser.options('Files')
  File "D:\Program Files\Python\Lib\configparser.py", line 661, in options
    raise NoSectionError(section) from None
configparser.NoSectionError: No section: 'Files'

注意:节名区别字母大小写。

判断节下是否存在某个键

>>> parser.has_option('Mail','mapi')
True
>>> parser.has_option('Mail','Mapi')
True
>>> parser.has_option('Mail','MAPI')
True
>>> parser.has_option('Mail','abc')
False
>>> parser.has_option('Mail','ABC')
False

注意:键名不区别字母大小写。

增加节点

>>> parser.add_section('Names')
>>> parser.sections()
['fonts', 'extensions', 'mci extensions', 'files', 'Mail', 'Names']
>>> parser.add_section('names')
>>> parser.sections()
['fonts', 'extensions', 'mci extensions', 'files', 'Mail', 'Names', 'names']

注意:增加已在节,会抛错DuplicateSectionError(section)

>>> parser.add_section('names')
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    parser.add_section('names')
  File "D:\Program Files\Python\Lib\configparser.py", line 1189, in add_section
    super().add_section(section)
  File "D:\Program Files\Python\Lib\configparser.py", line 645, in add_section
    raise DuplicateSectionError(section)
configparser.DuplicateSectionError: Section 'names' already exists

正确用法,配合has_section()一起使用

>>> if not parser.has_section('Level'):
...     parser.add_section('Level')
... 
>>> parser.sections()
['fonts', 'extensions', 'files', 'Mail', 'names', 'Level']

删除节点

>>> parser.sections()
['fonts', 'extensions', 'mci extensions', 'files', 'Mail', 'Names', 'names']
>>> parser.remove_section('Names')
True
>>> parser.remove_section('file')
False
>>> parser.remove_section('mci extensions')
True
>>> parser.sections()
['fonts', 'extensions', 'files', 'Mail', 'names']

注意:是否删除成功,由返回值True或False来判断。

增加节点的键

>>> parser.options('Mail')
['mapi']
>>> if not parser.has_option("Mail", "names"):
...     parser.set("Mail", "names", "")
... 
...     
>>> parser.options('Mail')
['mapi', 'names']

修改键值

与增加键一样用set(),但value参数不为空。

>>> parser.set("Mail", "names", "Hann")

或者写成:

parser.set(section="Mail", option="names", value="Hann")

保存修改结果

>>> parser.write(fp=open('exam.ini', 'w'))

注意:增删等改变ini文件内容的操作都要write才能得到保存。

获取键值

>>> parser.get("Mail", "names")
'Hann'
>>> parser.get("Mail", "Names")
'Hann'
>>> parser.get("mail", "Names")
Traceback (most recent call last):
  File "<pyshell#81>", line 1, in <module>
    parser.get("mail", "Names")
  File "D:\Program Files\Python\Lib\configparser.py", line 759, in get
    d = self._unify_values(section, vars)
  File "D:\Program Files\Python\Lib\configparser.py", line 1130, in _unify_values
    raise NoSectionError(section) from None
configparser.NoSectionError: No section: 'mail'

注意:再次证明节名区别大小写,键名不区别大小写。

获取键值时指定值的类型:getint,getfloat,getboolean

>>> parser.getint("Mail", "mAPI")
1
>>> parser.getfloat("Mail", "mapi")
1.0
>>> parser.getboolean("Mail", "mapi")
True

注意:一但所取值不能转为指定类型会报ValueError错误。

错:    return conv(self.get(section, option, **kwargs))
ValueError: invalid literal for int() with base 10: 'Tom'
或:    return conv(self.get(section, option, **kwargs))
ValueError: could not convert string to float: 'Tom'
或:    raise ValueError('Not a boolean: %s' % value)
ValueError: Not a boolean: Tom

获取节点所有键值

>>> parser.items('Mail')
[('mapi', '1'), ('name', '"Hann"'), ('names', 'Tom'), ('kates', '')]

其他读取方式

configparser的读取除了read和read_file从文件中读取还能从字串或字典中读取。

从字串中读取 read_string

字串的内容要与ini文件格式一样才能正常读取:

import configparser

config_string = """  
[DEFAULT]  
Name = Hann Yang
CodeAge = 16

[User]  
Username = boysoft2002
  
[CSDN HomePage]  
Url = https://blog.csdn.net/boysoft2002


Rank = 110
Blogs = 999
Visits = 3300000
VIP = True
Expert = True

"""  

parser = configparser.ConfigParser()  
parser.read_string(config_string)  

print(parser.get('CSDN HomePage', 'Url'))
print(parser.get('CSDN HomePage', 'Expert'))
从字典中读取 read_dict

 嵌套字典的格式也要与ini格式匹配才能正常读取:

import configparser

config_dict = {
    'DEFAULT': {
        'Name': 'Hann Yang',
        'CodeAge': 16
    },
    'User': {
        'Username': 'boysoft2002'
    },  
    'CSDN HomePage': {
        'Url': 'https://blog.csdn.net/boysoft2002',
        'Rank': 110,
        'Visits': 3300000,
        'VIP': True,
        'Expert': True
    }
}
  
parser = configparser.ConfigParser()
parser.read_dict(config_dict)

print(parser.get('CSDN HomePage', 'Url'))
print(parser.get('CSDN HomePage', 'Expert'))

完整示例代码

import configparser  
  
# 创建一个配置解析器  
parser = configparser.ConfigParser()  
  
# 读取INI文件  
parser.read('exam.ini')  
  
# 检查是否成功读取了文件  
if len(parser.sections()) == 0:  
    print("INI文件为空或未找到指定的节。")  
else:  
    # 获取所有节的列表  
    sections = parser.sections()  
    print("INI文件中的节:")  
    for section in sections:  
        print(section)  
  
    # 获取指定节下的所有选项  
    section_name = 'Mail'
    if section_name in parser:  
        options = parser[section_name]  
        print(f"节 '{section_name}' 中的选项:")  
        for option in options:  
            print(f"{option}: {parser[section_name][option]}")  
  
        # 获取指定节下的单个选项的值  
        option_name = 'Name'  # 假设我们要获取的选项的名字是 'example_option'  
        if option_name in options:  
            value = parser.get(section_name, option_name)  
            print(f"节 '{section_name}' 中 '{option_name}' 的值为:{value}")  
  
        # 修改指定节下的单个选项的值  
        new_value = 'Name'  
        parser.set(section_name, option_name, new_value)  
        print(f"已将节 '{section_name}' 中 '{option_name}' 的值修改为:{new_value}")  
  
        # 添加一个新的选项到指定节  
        new_option_name = 'new_option'  
        new_option_value = 'option_value'  
        parser.set(section_name, new_option_name, new_option_value)  
        print(f"已在节 '{section_name}' 中添加了新选项 '{new_option_name}',其值为:{new_option_value}")  
  
        # 删除指定节下的单个选项  
        parser.remove_option(section_name, new_option_name)  
        print(f"已删除节 '{section_name}' 中的选项 '{new_option_name}'")  
  
        # 添加一个新的节  
        new_section_name = 'new_section'  
        parser.add_section(new_section_name)  
        print(f"已添加新节 '{new_section_name}'")  
  
        # 将修改后的配置写回文件  
        with open('exam.ini', 'w') as configfile:  
            parser.write(configfile)  
        print("修改已写回INI文件。")  
    else:  
        print(f"INI文件中未找到节 '{section_name}'。")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/456883.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

linux下dlib静态库和动态库编译

本文讲述的linux系统下如何编译dlib的静态库和动态库方法。 dlib源码下载地址 dlib官网&#xff1a;dlib C LibraryGitHub - davisking/dlib: A toolkit for making real world machine learning and data analysis applications in C dlib源码的目录结构如下&#xff1a; 编…

【TB作品】MSP430单片机,音乐播放器,四首音乐,八音盒,Proteus仿真

文章目录 题目要求仿真结果实验报告&#xff1a;基于MSP430单片机的八音盒设计实验目的实验设备实验原理总结 代码和仿真图 题目要求 八音盒 本设计利用MSP430单片机结合内部定时器及LED/LCD,设计一个八音盒,按下单键可以演奏预先设置的歌曲旋律。 基本要求: 使用LED/LCD显示器…

格子表单GRID-FORM | 必填项检验 BUG 修复实录

格子表单/GRID-FORM已在Github 开源&#xff0c;如能帮到您麻烦给个星&#x1f91d; GRID-FORM 系列文章 基于 VUE3 可视化低代码表单设计器嵌套表单与自定义脚本交互文档网站搭建&#xff08;VitePress&#xff09;与部署&#xff08;Github Pages&#xff09;必填项检验 BUG…

AS-V1000 视频监控平台产品介绍:web客户端功能介绍(上)

目 录 一、引言 1.1 AS-V1000视频监控平台介绍 1.2 平台服务器配置说明 二、软件概述 2.1 软件用途 2.2 登陆界面 2.3 主界面 2.4 视频浏览 三、web端主要功能介绍 3.1 多画面风格 3.1.1风格切换 3.1.2 切换效果 3.2截屏 3.2.1 单画面截屏 3.2.2 …

cesium wall 扩散墙(动态立体墙效果 Primitive 方法)

cesium wall 扩散墙(动态立体墙效果)以下为源码直接复制可用 1、实现思路 1、此效果运用cesium 中 Primitive 方法,通过传入中心点、半径、顶点数、颜色来进行加载。 2、运用 Math 方法 对传进来的中心点、半径、定点数,来计算个顶点经纬度。 3、通过Primitive 方法中upda…

Vue3调用钉钉api,内嵌H5微应用单点登录对接

钉钉内嵌H5微应用单点登录对接 https://open.dingtalk.com/document/isvapp/obtain-the-userid-of-a-user-by-using-the-log-free 前端需要的代码 1、安装 dingtalk-jsapi npm install dingtalk-jsapi2、在所需页面引入 import * as dd from dingtalk-jsapi; // 引入钉钉a…

软件测试覆盖率

软件测试覆盖率简介 1、定义&#xff1a;覆盖率是用来度量测试完整性的一个手段&#xff0c;同时也是测试技术有效性的一个度量。2、计算&#xff1a;覆盖率&#xff08;至少被执行一次的item数&#xff09;/item的总数3、特点1&#xff09;通过覆盖率数据&#xff0c;可以检测…

【框架学习 | 第五篇】SpringMVC(常用注解、获取请求参数、域对象共享数据、拦截器、异常处理、上传/下载文件)

文章目录 1.SpringMVC简介1.1定义1.2主要组件1.3工作流程1.3.1简要流程1.3.2详细流程 1.4优缺点 2.常用注解3.获取请求参数3.1通过 HttpServletRequest 获取请求参数3.2通过控制器方法的形参获取请求参数3.2.1请求路径参数与方法形参一致3.2.2请求路径参数与方法形参不一致3.2.…

3、设计模式之工厂模式1(Factory)

工厂模式是什么&#xff1f;     工厂模式是一种创建者模式&#xff0c;用于封装和管理对象的创建&#xff0c;屏蔽了大量的创建细节&#xff0c;根据抽象程度不同&#xff0c;主要分为简单工厂模式、工厂方法模式以及抽象工厂模式。 简单工厂模式 看一个具体的需求 看一个…

【划重点】自动引流软件隐藏风险!?你不知道的网络危机与应对策略

先来看成果&#xff0c;评论888领取 在互联网快速发展的今天&#xff0c;自动引流软件以其高效的推广方式和便捷的操作&#xff0c;成为许多商家和个人提升网络知名度的重要工具。然而&#xff0c;这种看似无害的软件&#xff0c;却潜藏着不容忽视的网络安全风险。本文将深入解…

Linux操作系统启动流程

文章目录 1. Linux操作系统启动流程图2.运行流程&#xff08;1&#xff09; 加载BIOS&#xff08;2&#xff09; 读取MBR&#xff08;3&#xff09; GRUB引导&#xff08;4&#xff09; 加载Kernel&#xff08;5&#xff09; 设定Inittab运行等级&#xff08;6&#xff09; 加载…

如何布局马斯克推特上喊的meme币赛道

2024年的牛市正如火如荼的开展&#xff0c;截止当下&#xff0c;比特币已经站上了7.3万美元&#xff0c;远超2021年高点的6.9万美元&#xff0c;比特币的未来是一片大海。 除了比特币的一枝独秀之外&#xff0c;meme板块可以说是市场资金最青睐的。尤其是马斯克在X分享PEPE相关…

初步了解序列化和反序列化

01什么是序列化和反序列化 序列化是将对象转化为字符串以便存储的一种方式。而反序列化恰好是序列化的逆过程&#xff0c;反序列化会将字符串转化为对象供程序使用。 常见的php系列化和反系列化方式主要有&#xff1a;serialize&#xff0c;unserialize&#xff1b;json_enco…

LVGL移植到ARM开发板(GEC6818开发板)

LVGL移植到ARM开发板&#xff08;GEC6818开发板&#xff09; 一、LVGL概述 LVGL&#xff08;Light and Versatile Graphics Library&#xff09;是一个开源的图形用户界面库&#xff0c;旨在提供轻量级、可移植、灵活和易于使用的图形用户界面解决方案。 它适用于嵌入式系统…

四、MySQL

MySQL MySQL1.初识网站2.安装MySQL2.1 下载&#xff08;最重要的一点是路径中不能有中文&#xff0c;哪怕是同级目录也不行&#xff09;2.2安装补丁2.3安装2.4创建配置文件2.5初始化 3.启动MySQL4.连接测试4.1 设置密码4.2 查看已有的文件夹&#xff08;数据库&#xff09;4.3 …

【SSM】任务列表案例 基本CRUD SSM整合

文章目录 一、案例功能预览二、接口分析三、前端工程导入四、后端程序实现和测试4.1 准备4.2 功能实现4.2.1 分页查询显示4.2.2 添加计划4.2.2 删除计划4.2.3 修改计划 4.3 前后联调 一、案例功能预览 Github 地址 &#xff1a; ssm-integration-part 二、接口分析 学习计划…

【C++初阶】C++入门(上)

C的认识 ①什么是C&#xff1f; ​ C语言是结构化和模块化的语言&#xff0c;适合处理较小规模的程序。对于复杂的问题&#xff0c;规模较大的程序&#xff0c;需要高度的抽象和建模时&#xff0c;C语言则不合适。 ​ 于是1982年&#xff0c;Bjarne Stroustrup&#xff08;本…

激活函数理解

前言 为什么神经网中非要有各种各样的激活函数&#xff1f;他们有什么用&#xff1f;没有他们会怎样&#xff1f;常见的激活函数有哪些&#xff0c;他们都有什么特点&#xff1f; 如果我们不运用激活函数&#xff0c;神经网络的输出信号将仅仅是一个简单的线性函数。线性方程…

【DL经典回顾】激活函数大汇总(七)(CReLU RReLU附代码和详细公式)

激活函数大汇总&#xff08;七&#xff09;&#xff08;CReLU & RReLU附代码和详细公式&#xff09; 更多激活函数见激活函数大汇总列表 一、引言 欢迎来到我们深入探索神经网络核心组成部分——激活函数的系列博客。在人工智能的世界里&#xff0c;激活函数扮演着不可或…

Solidity 智能合约开发 - 基础:基础语法 基础数据类型、以及用法和示例

苏泽 大家好 这里是苏泽 一个钟爱区块链技术的后端开发者 本篇专栏 ←持续记录本人自学两年走过无数弯路的智能合约学习笔记和经验总结 如果喜欢拜托三连支持~ 本篇主要是做一个知识的整理和规划 作为一个类似文档的作用 更为简要和明了 具体的实现案例和用法 后续会陆续给出…
最新文章