Python读写ini文件的方法---from configparser import ConfigParser

1、读ini配置文件内容:

复制代码
#-*-encoding=utf-8-*-
# 测试ConfigParser
import os

# 导入ConfigParse包
import configparser
 
# 初始化
config = configparser.ConfigParser()
 
# 配置文件的绝对路径
config_path = os.path.dirname(os.path.realpath(__file__)) + "/config.ini"

# 读取配置文件
config.read(filenames=config_path,encoding='UTF-8')
 
# 获取配置中的所有section节点【返回值以列表方式存放了所有section节点名】
sections = config.sections()
 
# 返回指定section节点中的的所有option名称【返回值是列表的方式】
section_options = config.options(section="section")

# 返回指定的section节点中指定option的对应值
value = config.get(section="section", option="option")

# 配置文件中是否存在节点section,存在返回Ture,不存在返回false
config.has_section(section="section")

# 返回配置文件中指定section内所有的option以及对应的值value列表
config.item(section="section")
复制代码

2、写ini配置文件内容

复制代码

1、config=ConfigParser.ConfigParser() #创建ConfigParser实例

2、config.read(filenames=config_path,encoding='UTF-8') #读取配置文件

3、config.add_section(str) 添加一个配置文件节点(str)

4、config.set(section,option,value) 设置section节点中键名为option的值value

5、config.write(open(filename,'r+')) 写入配置文件

复制代码

 3、删除in配置文件内容

config.remove_option(section, option) 删除指定section节点下的option
config.remove_section(section) 删除指定的section节点内容

4、实例一:

复制代码
import configparser

from config import setting


# ini文件中 “[ ]”包含的为 section,section 下面为类似于字典类型的name - value 的配置内容;
class ReadConfig:
    def __init__(self):
        self.config = configparser.ConfigParser()
        self.path = setting.TEST_CONFIG
        self.config.read(self.path, encoding='UTF-8')

    # 返回指定section节点中的的所有option名称【返回值是列表的方式】
    def get_all_options(self, section):
        return self.config.options(section=section)

    # 返回配置中的所有section节点(返回值以列表方式存放了所有section节点名)
    def get_all_sections(self):
        return self.config.sections()

    # 读取指定配置文件
    def read_config(self, section, option):
        data = self.config.get(section, option)
        return data

    # 写入配置
    def write_config(self, section, option, value):
        # ①新建section节点,写入option
        if not self.config.has_section(section):
            # if section not in self.get_all_sections():
            self.config.add_section(section)
            self.config.set(section, option, value)
        # ②更改section节点中的option(section已存在)
        elif self.config.has_section(section):
            # elif section in self.get_all_sections():
            self.config.set(section, option, value)  # 无论option是否在指定section中存在,都会新建section子节点
        # 修改文件后需要写入保存
        self.config.write(open(self.path, "w"))

    # 删除指定的section或者option
    def remove_config(self, section, option=None):
        # ①指定section下的option为空,删除整个section
        if option is None:
            self.config.remove_section(section)
            # 修改文件后需要写入保存
            self.config.write(open(self.path, "w"))
        # ②将要删除的option存在且存在于指定的section中,只删除option
        elif option is not None and option in self.get_all_options(section=section):
            self.config.remove_option(section, option)
            # 修改文件后需要写入保存
            self.config.write(open(self.path, "w"))
        # ③ 将要删除的option存在但是不存在于指定的section中,无法删除option
        elif option is not None and option not in self.config.options(section=section):
            print("数据有误,请重新传入!")


if __name__ == '__main__':
    print(ReadConfig().read_config("project_questionnaire", "ip"))
    # ReadConfig().write_config("url_info", "token", "写入token的内容")
复制代码

5、实例二:

复制代码
import configparser

class cconfigparser(object):
    def __init__(self,conf_path):
        self.fpath = conf_path
        self.cf = configparser.ConfigParser()
        self.cf.read(self.fpath,encoding='UTF-8')

    def write(self):
        filename = open(self.fpath,'w')
        self.cf.write(filename)
        filename.close()

    # 添加指定的节点
    def add_section(self,section):
         sections = self.cf.sections()
         if section in sections:
             return
         else:
             self.cf.add_section(section)

    # 删除节点
    def remove_section(self,section):
        return self.cf.remove_section(section)

    #返回文件中的所有sections
    def sections(self):
        return self.cf.sections()

    # 获取节点下option对应的value值
    def get(self,section,option):
        return self.cf.get(section,option)

    # 在指定的section下添加option和value值
    def set(self,section,option,value):
        if self.cf.has_section(section):
            self.cf.set(section,option,value)

    #移除指定section点内的option
    def remove_option(self,section,option):
        if self.cf.has_section(section):
            resutl = self.cf.remove_option(section,option)
            return resutl
        return False

    # 返回section内所有的option和value列表
    def items(self,section):
        return self.cf.items(section)

    # 返回section所有的option
    def options(self,section):
        return self.cf.options(section)
复制代码

 

【注意】

python的ini配置文件读取模块 configparser 注意的问题:

一般情况都是使用 ConfigParser() 类初始化配置对象后在进行.ini文件的读取但是当.ini配置文件中有 %(filename)s 这种格式的配置的时候可能会出现以下问题:
configparser.InterpolationMissingOptionError: Bad value substitution: option 'output_fmt' in section 'output' contains an interpolation key 'asctime' which is not a valid option name.Raw value: '"%(asctime)s-%(levelname)s-%(filename)s-%(name)s-日志信息:%(message)s"'

解决办法:

将 configparser() 类换成了 RawConfigParser()类;如下代码:

复制代码
import configparser

from config.conf import cm

HOST = 'HOST'


class ReadConfig(object):
    """配置文件"""

    def __init__(self):
        self.config = configparser.RawConfigParser()  # 当有.ini配置文件中存在'%'符号时请使用RawConfigParser读取
        self.config.read(cm.ini_file, encoding='utf-8')

    def _get(self, section, option):
        """获取"""
        return self.config.get(section, option)

    def _set(self, section, option, value):
        """更新"""
        self.config.set(section, option, value)
        with open(cm.ini_file, 'w') as f:
            self.config.write(f)

    @property
    def url(self):
        return self._get(HOST, HOST)


ini = ReadConfig()

if __name__ == '__main__':
    print(ini.url)
复制代码

 

 
posted @   习久性成  阅读(1261)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示