使用Python在配置文件中写评论

2024-04-27 15:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

########################
# 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')

Tags: configfoo配置文件comment评论barsectiondo
1条回答
网友
1楼 · 发布于 2024-04-27 15:23:24

从文档中:

以“35;”或“;”开头的行将被忽略,并可用于提供注释。

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

示例:

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

相关问题 更多 >