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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM