Python 内置模块之 ConfigParser - 解析 ini 文件

ini配置文件是被configParser直接解析然后再加载的,如果只是修改配置文件,并不会改变已经加载的配置

INI文件结构简单描述

INI文件就是扩展名为“ini”的文件。在Windows系统中,INI文件是很多,最重要的就是“System.ini”、“System32.ini”和“Win.ini”。
该文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件,来改变应用程序和系统的很多配置。但自从Windows 95的退出,在Windows系统中引入了注册表的概念,INI文件在Windows系统的地位就开始不断下滑,这是因为注册表的独特优点,使应用程序和系统都把许多参数和初始化信息放进了注册表中。但在某些场合,INI文件还拥有其不可替代的地位。

INI文件结构

INI文件是一种按照特点方式排列的文本文件。每一个INI文件结构都非常类似,由若干段落(section)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键词(keyword)和一个等号,等号右边的就是关键字对应的值(value)。其一般形式如下:

[Section1]  
KeyWord1 = Valuel 
KeyWord2 = Value2 
……  
[Section2]  
KeyWord3 = Value3 
KeyWord4 = Value4  

其中:[Section1]用来表示一个段落。因为INI文件可能是项目中共用的,所以使用[Section]段名来区分不同用途的参数区。

例如:[Section1]表示传感器灵敏度参数区;[Section2 ]表示测量通道参数区等等。KeyWord1=value1 用来表示一个参数名和值。

格式

INI文件由节、键、值组成。

[section]

参数(键=值)

name=value

注解

注解使用分号表示(;)。在分号后面的文字,直到该行结尾都全部为注解。

; comment text

linux 配置文件使用 # 注释;

# comment text

Python ConfigParser

Python 标准库的 ConfigParser 模块提供了一套完整的 API 来读取和操作配置文件。

在python 3 中ConfigParser模块名已更名为configparser。
configparser模块支持读取.conf和.ini等类型的文件。
但是存在一些缺陷,无法识别section的大小写,无法读取文件注释,这样修带有注释的配置文件时就会存在问题。

操作配置文件

配置文件实例化

# 实例化 CoinfigParser 并加载配置文件
config = ConfigParser.SafeConfigParser()
config.read('config.ini')

# 读取配置文件内容,f必须是unicode
config.read_file(f, source=None)
# 从字符串解析配置数据
config.read_string(string, source=’’)
# 从词典解析配置数据
config.read_dict(dictionary, source=’’)

配置文件的读取和修改

# sections(): 得到所有的section,并以列表的形式返回
config.sections()

# defaults():返回一个包含实例范围默认值的词典
config.defaults()

# 添加一个新的section
config.add_section(section)

# 判断是否有section
config.has_section(section)

# 得到该section的所有option
config.options(section)

# items 得到section的所有键值对
config.items(option)

# 判断如果section和option都存在则返回True否则False
config.has_option(section, option)

# 得到section中option的值,返回为string类型
config.get(section, option, *, raw=False, vars=None[, fallback])

# 得到section中option的值,返回为int类型
config.getint(section,option)

# 得到section中option的值,返回为float类型
config.getfloat(section,option)

# 得到section中option的值,返回为boolean类型
config.getboolean(section, option)

# 对section中的option进行更新,如果没有相应的option,会新增
config.set(section, option, value)

# 从指定section移除option
config.remove_option(section, option)

# 移除section
config.remove_section(section)

配置文件的写入

with open("config.ini", "w+") as f:
    config.write(f)

# 将配置信息输出到标准输出
config.write(sys.stdout)

# 将配置文件输出到文件
config.write(open('new_book.info','w'))

示例

import threading
import configparser
class Config(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read("config.ini")

    # single mode,the config file must be control by the only one
    def __new__(cls, *arg, **kwargs):
        if not hasattr(Config, "_instance"):
            with Config._instance_lock:
                if not hasattr(Config, "_instance"):
                    Config._instance = object.__new__(cls)
        return Config._instance

    def get_config(self, section, k):
        return self.config.get(section, k)

    def get_section(self):
        return self.config.sections()

    def get_section_all_key(self, section):
        return self.config.options(section)

    def add_section(self, section):
        self.config.add_section(section)

    def update_k(self, section, k, v):
        # 更新相应的k,如果没有对应的k,会自动创建 k,判断k时不区分大小写。
        self.config.set(section, k, v)

    def remove_section(self, section):
        self.config.remove_section(section)

    def remove_k(self, section, k):
        self.config.remove_option(section, k)

    def save_config(self):
        with open("config.ini", "w+") as f:
            self.config.write(f)

操作字典的方式操作文件

"""生成configparser配置文件 ,字典的形式"""
import configparser 
config = configparser.ConfigParser()


# 第一种写法
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

# 第二种写法
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

# 第三种写法
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
 
config['DEFAULT']['ForwardX11'] = 'yes'

# 写入后缀为.ini的文件
with open('example.ini', 'w') as configfile:
    config.write(configfile)
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值