以这个非常简单的典型配置文件为例:
[DEFAULT]ServerAliveInterval = 45ComPRession = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no1、config parser 操作跟dict 类似,在数据存取方法基本一致
>> import configparser>>> config = configparser.ConfigParser()>>> config.sections()[]>>> config.read('example.ini')['example.ini']>>> config.sections()['bitbucket.org', 'topsecret.server.com']>>> 'bitbucket.org' in configTrue>>> 'bytebong.com' in configFalse>>> config['bitbucket.org']['User']'hg'>>> config['DEFAULT']['Compression']'yes'>>> topsecret = config['topsecret.server.com']>>> topsecret['ForwardX11']'no'>>> topsecret['Port']'50022'>>> for key in config['bitbucket.org']: print(key)...usercompressionlevelserveraliveintervalcompressionforwardx11>>> config['bitbucket.org']['ForwardX11']'yes'2、默认配置项[DEFAULT]section 的默认参数会作用于其他Sections3、数据类型 config parsers 不会猜测或自动分析识别config.ini参数的数据类型,都会按照字符串类型存储,如果需要读取为其他数据类型,需要自定义转换。 特殊bool值:对于常见的布尔值’yes’/’no’, ‘on’/’off’, ‘true’/’false’ 和 ‘1’/’0’,提供了getboolean()方法。4、获取参数值方法 get() 使用get()方法获取每一参数项的配置值。 如果一般Sections 中参数在[DEFAULT]中也有设置,则get()到位[DEFAULT]中的参数值。5、参数分隔符可以使用‘=’或‘:’(默认)6、可以使用‘#’或‘;’(默认)添加备注或说明[Simple Values]key=valuespaces in keys=allowedspaces in values=allowed as wellspaces around the delimiter = obviouslyyou can also use : to delimit keys from values[All Values Are Strings]values like this: 1000000or this: 3.14159265359are they treated as numbers? : nointegers, floats and booleans are held as: stringscan use the API to get converted values directly: true[Multiline Values]chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day[No Values]key_without_valueempty string value here =[You can use comments]# like this; or this# By default only in an empty line.# Inline comments can be harmful because they prevent users# from using the delimiting characters as parts of values.# That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too?7、写配置常见做法:
config.write(open('example.ini', 'w'))合理做法:
with open('example.ini', 'w') as configfile: config.write(configfile)待续。。。。。。
新闻热点
疑难解答