python configparser 空格_python的ConfigParser模块

简介

ConfigParser模块在python3中修改为configparser.这个模块定义了一个ConfigParser类,该类的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同

该模块的作用 就是使用模块中的RawConfigParser()、ConfigParser()、 SafeConfigParser()这三个方法,创建一个对象使用对象的方法对指定的配置文件做增删改查 操作。

配置文件有不同的片段组成和Linux中repo文件中的格式类似:

格式:

[section]

name=value

或者

name: value

"#" 和";" 表示注释

[DEFAULT] #设置默认的变量值,初始化

[My Section]

foodir: %(dir)s/whatever

dir=frob

long: this value continues

in the next line

方法

下面这三种方式使用时,切记注意

在调用这三个函数时,切记这三个函数会将调用optionxform(),在传递键值对数据时,会将键名全部转化为小写。

RawConfigParser()

ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]])

defaults : 如果指定默认值,则使用默认值的键值对

dict_type:使用新的section的键值对

allow_no_value :默认是False,如果是True,表示可以接收空值(None)

return:对象

不支持可变参数,在section中不能存在%()s

ConfigParser()

ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])

在default中必须出现%()s

SafeConfigParser()

ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]])

更加智能化,在section中是否存在%()s会自动判断

传递参数使用函数optionxform(),foo %(bar)s 和 foo %(BAR)s是相同的,optionxform()会将大写字母全部转换为小写。

解决自动小写的问题

>>> custom = configparser.RawConfigParser()

>>> custom.optionxform = lambda option: option

>>> custom.read_string(config)

或者

>>> cfgparser = ConfigParser()

>>> cfgparser.optionxform = str

注意:在读取配置文件时,在调用optionxform()之前,选项名称周围的空格将被去掉。

或者重写函数

class MyConfigParser(configparser.ConfigParser):

def optionxform(self, optionstr):

return optionstr

config = MyConfigParser()

ConfigParser常用参数

config = conf.ConfigParser(allow_no_value=True,inline_comment_prefixes=('#', ';'),empty_lines_in_values=False)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值