python 读写INI篇(INI)

python 读写INI篇(INI)

文章目录

  • python 读写INI篇(INI)
    • 一、ini使用环境(Window)
    • 二、python环境(configparser库)
    • 三、.ini文件示例(config.ini)
    • 四、文件读取
    • 五、文件修改和写入
    • 六、文件内容删除
    • 七、模块代码示例

一、ini使用环境(Window)

‌INI文件主要在Windows操作系统中使用‌。INI文件,即初始化文件(Initialization File),是一种用于存储程序配置信息的文本文件,通常以“.ini”作为文件扩展名。INI文件由多个部分组成,每个部分称为一个节(section),每个节包含多个键值对(key-value pairs),用于存储配置信息,如应用程序的设置或用户偏好‌。

二、python环境(configparser库)

configparser是Python标准库的一部分,而不是第三方库‌。configparser是Python标准库中的一个模块,用于读取、解析和写入.ini格式的配置文件‌,可以直接用

import configparser

三、.ini文件示例(config.ini)

; 这是工具信息
[INFO]
UserName = admin
PassWord = 123456
Status = True
Auther = Jensen

; 这是工具地址
[地址]
RootPath = ./Config/config.ini
CodePath = 这是一个地址

[config]
module = ios

四、文件读取

import configparser
import os
root_path = os.path.split(os.path.realpath(__file__))[0]

# 配置解析器
cf = configparser.ConfigParser()
# 读取 INI 文件
cf.read(root_path + '/Config.ini')

""" 获取INI 信息 """
# 读取 str 方式返回
cf_UserName = cf.get('INFO', "UserName")
print(cf_UserName, type(cf_UserName))

# 读取 int 方式返回
cf_Password = cf.getint('INFO', "Password")
print(cf_Password, type(cf_Password))

# 读取 boolean 方式返回
cf_Status = cf.getboolean('INFO', "Status")
print(cf_Status, type(cf_Status))

""" 获取INI 地址信息 """
# 支持 "部分名" 中文
cf_RootPath = cf.get('地址', "RootPath")
print(cf_RootPath, type(cf_RootPath))

# 支持 "值" 中文
cf_CodePath = cf.get('地址', "CodePath")
print(cf_CodePath, type(cf_CodePath))

# 获取搜索 "部分名" 是否存在
info_exists = cf.has_section("INFO")
print("info_exists:", info_exists, type(info_exists))

结果:
cf_UserName: admin
cf_Password: 123456
cf_Status: True
cf_RootPath: ./Config/config.ini
cf_CodePath: 这是一个地址
info_exists: True

五、文件修改和写入

删除和修改文件内容均需要重新写入

cf = configparser.ConfigParser()
cf.read(self.path)
if not cf.has_section("config"):
    cf.add_section("config")       	# 如果 section 不存在,则创建
cf.set("config", "Name", "admin")   # 如果 option 不存在,则创建,存在则修改
cf.write(open(root_path + '/Config.ini, "w"))

六、文件内容删除

删除和修改文件内容均需要重新写入

cf = configparser.ConfigParser()
cf.read(self.path)
cf.remove_option(section, option)
cf.write(open(self.path, "w"))

七、模块代码示例

import configparser

class RW_Configparser:
    def __init__(self, path):
        self.cf = configparser.ConfigParser()
        self.path = path                                            # 可以多个文件读写
        self.cf.read(self.path)

    def Get_All(self):
        All = ""
        for section in self.cf.sections():                          # 获取所有的section名
            print(f"[{section}]")                                   # 打印section名
            for option in self.cf.options(section):                 # 获取该section下的所有option名
                print(f"{option} = {self.cf[section][option]}")
                All += f"{option} = {self.cf[section][option]}\n"   # 打印option名和值
        return All                                              

    def Get_Configparser(self, section=None, option=None):
        try:
            value = self.cf.get(section, option)
            print(value)
            return value
        except configparser.NoSectionError:
            print("Section {} not exist".format(section))
            return "Section {} not exist".format(section)
        except configparser.NoOptionError:
            print("option {} not exist in section {}".format(option, section))
            return "option {} not exist in section {}".format(option, section)

    def Get_Configparser_Int(self, section=None, option=None):
        try:
            value_int = self.cf.getint(section, option)
            print(value_int)
            return value_int
        except configparser.NoSectionError:
            print("Section {} not exist".format(section))
            return "Section {} not exist".format(section)
        except configparser.NoOptionError:
            print("option {} not exist in section {}".format(option, section))
            return "option {} not exist in section {}".format(option, section)

    def Get_Configparser_Boolean(self, section=None, option=None):
        try:
            value_boolean = self.cf.getboolean(section, option)
            print(value_boolean)
            return value_boolean
        except configparser.NoSectionError:
            print("Section {} not exist".format(section))
            return "Section {} not exist".format(section)
        except configparser.NoOptionError:
            print("option {} not exist in section {}".format(option, section))
            return "option {} not exist in section {}".format(option, section)

    def Set_Configparser(self, section, option, param):
        if not self.cf.has_section(section):
            self.cf.add_section(section)       # 如果 section 不存在,则创建
        self.cf.set(section, option, param)    # 如果 option 不存在,则创建,存在则修改
        self.cf.write(open(self.path, "w"))
        print("Set configparser success for section = [{}], option = [{}], param = [{}]".format(section, option, param))
        return "Set configparser success for section = [{}], option = [{}], param = [{}]".format(section, option, param)

    def Remove_Configparser(self, section=None, option=None):
        if (self.cf.has_section(section)) and (option):
            self.cf.remove_option(section, option)
            self.cf.write(open(self.path, "w"))
            print("remove configparser success for section = [{}], option = [{}]".format(section, option))
            return "remove configparser success for section = [{}], option = [{}]".format(section, option)
        elif self.cf.has_section(section) and (not option):
            self.cf.remove_section(section)
            self.cf.write(open(self.path, "w"))
            print("remove configparser success for section = [{}]".format(section))
            return "remove configparser success for section = [{}]".format(section)
        else:
            print("Section {} not exist".format(section))
            return "Section {} not exist".format(section)

if __name__ == "__main__":
    import os
    code_root_path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]

    # == with open('config.ini', 'w') as configfile:
    #       config.write(configfile)
    # == config.write(open(self.path, "w"))

    RW_Configparser = RW_Configparser(code_root_path + "/config.ini")
    # RW_Configparser.Get_All()

    Get_Configparser = RW_Configparser.Get_Configparser("INFO", "username")
    
    Set_Configparser = RW_Configparser.Set_Configparser("config2", "platformname3", "ios")
    Set_Configparser = RW_Configparser.Set_Configparser("config2", "platformname4", "android")

    # Remove_Configparser = RW_Configparser.Remove_Configparser("config2", "platformname4")
    # Remove_Configparser = RW_Configparser.Remove_Configparser("config2")

如转载此文请联系我征得本人同意,并标注出处及本博主名,谢谢 !

你可能感兴趣的:(python,基础,python,开发语言)