以這個非常簡單的典型配置文件為例:
[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)待續。。。。。。
新聞熱點
疑難解答