文章目录
- configparser
- ConfigParser类
configparser
configparser即配置文件解析器,一般windows下的配置文件多为ini
格式,INI文件由段落组成,每个段落标题用[]
括起来,每个段落包含一些键值对,例如Windows每个文件夹下都会有一个隐藏文件Desktop.ini
,其内容大致为
[.ShellClassInfo]
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770
IconResource=%SystemRoot%\system32\imageres.dll,-112
IconFile=%SystemRoot%\system32\shell32.dll
IconIndex=-235
在Python中,configparser
模块提供了对INI文件的读写功能,下面新建一个ConfigParser
类,并填充一些内容
import configparser
# 下面这些代码来自python的文档
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['Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
# 将配置文件保存为example.ini
with open('example.ini', 'w') as cfFile:
config.write(cfFile)
则example.ini
中的内容为
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
port = 50022
forwardx11 = no
ConfigParser类
ConfigParser
类包含了dict
中的clear
, get
, items
, keys
, pop
, popitem
, setdefault
, update
, values
等方法,例如
>>> list(config.keys())
['DEFAULT', 'bitbucket.org', 'topsecret.server.com']
>>> list(config.values())
[<Section: DEFAULT>, <Section: bitbucket.org>, <Section: topsecret.server.com>]
此外,ConfigParser
还提供了更便捷的两个无参函数,用以输出段落和段落中的字典
>>> config.sections() #不包含DEFAULT的section
['bitbucket.org', 'topsecret.server.com']
>>> config.defaults() #所有section中的键值对
{'serveraliveinterval': '45', 'compression': 'yes', 'compressionlevel': '9', 'forwardx11': 'yes'}
ConfigParser
类可以通过remove_option
和remove_section
键值对或者段落,例如
>>> config.remove_option("DEFAULT","compression")
True
>>> for key in config["DEFAULT"]:print(key)
...
serveraliveinterval
compressionlevel #compression被删除了
forwardx11
>>> dict(config)
{'DEFAULT': <Section: DEFAULT>, 'bitbucket.org': <Section: bitbucket.org>, 'topsecret.server.com': <Section: topsecret.server.com>}
>>> config.remove_section("topsecret.server.com")
True
>>> dict(config) #topsecret.server.com被删除了
{'DEFAULT': <Section: DEFAULT>, 'bitbucket.org': <Section: bitbucket.org>}
然后又可以通过add_section
添加段落,通过has_section
判断是否存在段落,以及has_option
判断是否存在某选项
>>> config.has_section("topsecret.server.com")
False
>>> config.add_section("topsecret.server.com")
>>> config.has_section("topsecret.server.com")
True
由于在ini
中所有的键值对都默认为字符串,所以ConfigParser
类提供了快速转变数据类型的函数getboolean
, getfloat
, getint
,
>>> config.get("DEFAULT","compressionlevel")
'9' #正常输出为字符串
>>> config.getint("DEFAULT","compressionlevel")
9
最后,附上标准库中对ConfigParser 对象
的解读
class configparser.ConfigParser(defaults,dict_type, allow_no_value, delimiters, comment_prefixes, inline_comment_prefixes, strict, empty_lines_in_values, default_section, interpolation=, converters={})
- defaults 主配置解析器。 当给定 defaults 时,它会被初始化为包含固有默认值的字典。
- dict_type 当给定时,将被用来创建包含节、节中的选项以及默认值的字典。
- delimiters 用作分隔键与值的子字符串的集合。 默认为**(‘=’, ‘:’)**。
- comment_prefixes 用作在否则为空行的注释的前缀子字符串的集合。 注释可以被缩进。
- inline_comment_prefixes 用作非空行的注释的前缀子字符串的集合。
- strict 为 True (默认值) 时,解析器在从单个源(文件、字符串或字典)读取时将不允许任何节或选项出现重复,否则会引发异常。
- empty_lines_in_values 为 False (默认值: True) 时,每个空行均表示一个选项的结束。 在其他情况下,一个多行选项内部的空行会被保留为值的一部分。
- allow_no_value 为 True (默认值: False) 时,将接受没有值的选项;此种选项的值将为 None 并且它们会以不带末尾分隔符的形式被序列化。
- default_section 它将指定存放其他节的默认值和用于插值的特殊节的名称 (通常命名为 “DEFAULT”)。 该值可通过使用 default_section 实例属性在运行时被读取或修改。
- interpolation 提供自定义处理程序的方式来定制。 None 可用来完全禁用插值,ExtendedInterpolation() 提供了一种更高级的变体形式,它的设计受到了 zc.buildout 的启发。 插值中使用的所有选项名称将像任何其他选项名称引用一样通过 optionxform() 方法来传递。 例如,使用 optionxform() 的默认实现(它会将选项名称转换为小写形式)时,值 foo %(bar)s 和 foo %(BAR)s 是等价的。
- converters 为一个字典,每个键代表一个类型转换器的名称而每个值则为实现从字符串到目标数据类型的转换的可调用对象。 每个转换器会获得其在解析器对象和节代理上对应的 get*() 方法。