python INI文件操作与configparser内置库

news2024/9/26 3:20:10

目录

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.coloradmin.cn/o/1507314.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

JAVA实战开源项目:超市自助付款系统(Vue+SpringBoot)

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、研究内容2.1 商品类型模块2.2 商品模块2.3 超市账单模块 三、界面展示3.1 登录注册模块3.2 超市商品类型模块3.3 超市商品模块3.4 商品购买模块3.5 超市账单模块 四、部分源码展示4.1 实体类定义4.2 控制器接口 五、配套文档展示六、…

【APP逆向】酒仙网预约茅台(附带源码)

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 所属的专栏:爬虫实战,零基础、进阶教学 景天的主页:景天科技苑 文章目录 酒仙网预约抢购茅台1.抓包分析,账户名和密码登录2.短信登录3.登录+茅台预约 密码登录酒仙网预约抢购茅台 目标:账号登…

Fortran语法介绍(三)

个人专栏—ABAQUS专栏 Abaqus2023的用法教程——与VS2022、oneAPI 2024子程序的关联方法 Abaqus2023的用法教程——与VS2022、oneAPI 2024子程序的关联方法Abaqus有限元分析——有限元网格划分基本原则 Abaqus有限元分析——有限元网格划分基本原则各向同性线弹性材料本构模型…

吴恩达深度学习笔记:神经网络的编程基础2.1-2.3

目录 第一门课&#xff1a;神经网络和深度学习 (Neural Networks and Deep Learning)第二周&#xff1a;神经网络的编程基础 (Basics of Neural Network programming)2.1 二分类(Binary Classification)2.2 逻辑回归(Logistic Regression)2.3 逻辑回归的代价函数&#xff08;Lo…

Gin 获取请求参数

POST 请求参数 Gin 获取Post请求URL参数有三种方式 func (c *Context) PostForm(key string) string func (c *Context) DefaultPostForm(key, defaultValue string) string func (c *Context) GetPostForm(key string) (string, bool)大多数情况下使用的是application/x-www…

Electron程序如何在MacOS下获取相册访问权限

1.通过entitiment.plist&#xff0c;在electron-builder签名打包时&#xff0c;给app包打上签名。最后可以通过codesign命令进行验证。 TestPhotos.plist electron-builder配置文件中加上刚刚的plist文件。 通过codesign命令验证&#xff0c;若出现这个&#xff0c;则说明成…

day60 安装MySql数据库

1如何安装MySQL数据库 2数据库概念 3数据库语言 1 SQL&#xff08;数据结构化查询语句&#xff09; 2分类 1数据库查询语言DQL select 2数据库操作语言DML insert&#xff0c;update&#xff0c;delete 3数据库定义语言DDL create&#xff0c;alter修改&am…

MySQL--优化(索引--聚簇和非聚簇索引)

MySQL–优化&#xff08;索引–聚簇和非聚簇索引&#xff09; 定位慢查询SQL执行计划索引 存储引擎索引底层数据结构聚簇和非聚簇索引索引创建原则索引失效场景 SQL优化经验 一、聚簇索引 聚簇索引&#xff1a;将数据存储与索引放到了一块&#xff0c;索引结构的叶子节点保存…

C语言连接【MySQL】

稍等更新图片。。。。 文章目录 安装 MySQL 库连接 MySQLMYSQL 类创建 MySQL 对象连接数据库关闭数据库连接示例 发送命令设置编码格式插入、删除或修改记录查询记录示例 参考资料 安装 MySQL 库 在 CentOS7 下&#xff0c;使用命令安装 MySQL&#xff1a; yum install mysq…

明日周刊-第1期

打算开一个新的专栏&#xff0c;专门记录一周发生的事情以及资源共享&#xff0c;那么就从第一期开始吧。 1. 一周热点 人工智能技术突破&#xff1a;可能会有关于人工智能领域的最新研究成果&#xff0c;例如新算法的开发、机器学习模型的提升或者AI在不同行业的应用案例。 量…

PT:dmsa如何设置don‘t use

我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧? 拾陆楼知识星球入口 往期文章链接: PT: 基于Multi Voltage的physical aware DMSA PT: DMSA remote_execute { \ define_user_attribu

Tomcat源码解析(四):StandardServer和StandardService

Tomcat源码系列文章 Tomcat源码解析(一)&#xff1a;Tomcat整体架构 Tomcat源码解析(二)&#xff1a;Bootstrap和Catalina Tomcat源码解析(三)&#xff1a;LifeCycle生命周期管理 Tomcat源码解析(四)&#xff1a;StandardServer和StandardService 文章目录 前言一、Standar…

大数据赋能,能源企业的智慧转型之路

在数字洪流中&#xff0c;大数据已经成为推动产业升级的新引擎。特别是在能源行业&#xff0c;大数据的应用正引领着一场深刻的智慧转型。今天&#xff0c;我们就来探讨大数据如何在能源企业中发挥其独特的魅力&#xff0c;助力企业提效降本&#xff0c;实现绿色发展。 动态监控…

R语言读取大型NetCDF文件

失踪人口回归&#xff0c;本篇来介绍下R语言读取大型NetCDF文件的一些实践。 1 NetCDF数据简介 先给一段Wiki上关于NetCDF的定义。 NetCDF (Network Common Data Form) is a set of software libraries and self-describing, machine-independent data formats that support…

光线追踪11 - Positionable Camera(可定位相机)

相机和介质一样&#xff0c;调试起来很麻烦&#xff0c;所以我总是逐步开发我的相机。首先&#xff0c;我们允许可调节的视野&#xff08;fov&#xff09;。这是渲染图像从一边到另一边的视觉角度。由于我们的图像不是正方形的&#xff0c;水平和垂直的视野是不同的。我总是使用…

mybatis基础操作(三)

动态sql 通过动态sql实现多条件查询&#xff0c;这里以查询为例&#xff0c;实现动态sql的书写。 创建members表 创建表并插入数据&#xff1a; create table members (member_id int (11),member_nick varchar (60),member_gender char (15),member_age int (11),member_c…

【探索程序员职业赛道:挑战与机遇】

💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学习,不断总结,共同进步,活到老学到老导航 檀越剑指大厂系列:全面总结 jav…

微信小程序(五十三)修改用户头像与昵称

注释很详细&#xff0c;直接上代码 上一篇 新增内容&#xff1a; 1.外界面个人资料基本模块 2.资料修改界面同步问题实现&#xff08;细节挺多&#xff0c;考虑了后期转服务器端的方便之处&#xff09; 源码&#xff1a; app.json {"window": {},"usingCompone…

什么是5G边缘计算网关?

随着5G技术的飞速发展和普及&#xff0c;边缘计算作为5G时代的关键技术之一&#xff0c;正日益受到业界的关注。而5G边缘计算网关&#xff0c;作为连接5G网络和边缘计算节点的桥梁&#xff0c;扮演着至关重要的角色。HiWoo Box&#xff0c;作为一款卓越的5G边缘计算网关&#x…

【Spring云原生系列】SpringBoot+Spring Cloud Stream:消息驱动架构(MDA)解析,实现异步处理与解耦合

&#x1f389;&#x1f389;欢迎光临&#xff0c;终于等到你啦&#x1f389;&#x1f389; &#x1f3c5;我是苏泽&#xff0c;一位对技术充满热情的探索者和分享者。&#x1f680;&#x1f680; &#x1f31f;持续更新的专栏《Spring 狂野之旅&#xff1a;从入门到入魔》 &a…