使用python在配置文件中写注释

时间:2012-10-12 06:42:22

标签: python comments configparser

我需要在Python中通过ConfigParser库在 runtime 生成的配置文件中写一些注释。

我想写一个完整的描述性评论,如:

########################
# FOOBAR section 
# do something 
########################
[foobar]
bar = 1
foo = hallo

代码应如下所示:

我在同一时刻插入评论和配置选项。

import ConfigParser

config = ConfigParser.ConfigParser()

config.insert_comment("##########################") # This function is purely hypothetical 
config.insert_comment("# FOOBAR section ")
....

config.add_section('foobar')
config.set('foobar', 'bar', '1')
config.set('foobar', 'foo', 'hallo')

1 个答案:

答案 0 :(得分:6)

来自文档:

以'#'或';'开头的行被忽略,可用于提供评论。

配置文件可能包含注释,前缀为特定字符(#和;)。注释可以单独显示在空行中,也可以输入包含值或节名称的行。在后一种情况下,它们需要在空白字符前面被识别为注释。 (仅用于向后兼容;启动内联注释,而#不启用。)

示例:

conf.set('default_settings', '; comment here', '')

[default_settings]
    ; comment here = 
    test = 1

config = ConfigParser.ConfigParser()
config.read('config.ini')
print config.items('default_settings')

>>>
[('test','1')] # as you see comment is not parsed
相关问题