如何在段内的给定文件中写注释?
如果我有:
import ConfigParser
with open('./config.ini', 'w') as f:
conf = ConfigParser.ConfigParser()
conf.set('DEFAULT', 'test', 1)
conf.write(f)
我会得到这个文件:
[DEFAULT]
test = 1
但是如何在[DEFAULT]
部分中获得包含注释的文件,例如:
[DEFAULT]
; test comment
test = 1
我知道我可以通过以下方式将代码写入文件:
import ConfigParser
with open('./config.ini', 'w') as f:
conf = ConfigParser.ConfigParser()
conf.set('DEFAULT', 'test', 1)
conf.write(f)
f.write('; test comment') # but this gets printed after the section key-value pairs
这是ConfigParser的可能吗?而且我不想尝试另一个模块,因为我需要尽可能地将我的程序保持为“库存”。
如果您具有Version> = 2.7,则可以使用allow_no_value选项
这个片段:
import ConfigParser
config = ConfigParser.ConfigParser(allow_no_value=True)
config.add_section('default_settings')
config.set('default_settings', '; comment here')
config.set('default_settings', 'test', 1)
with open('config.ini', 'w') as fp:
config.write(fp)
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read('config.ini')
print config.items('default_settings')
将创建一个像这样的ini文件:
[default_settings]
; comment here
test = 1
您可以创建以#或;开头的变量;字符:
conf.set('default_settings', '; comment here', '')
conf.set('default_settings', 'test', 1)
创建的conf文件是
[default_settings]
; comment here =
test = 1
ConfigParser.read函数不会解析第一个值
config = ConfigParser.ConfigParser()
config.read('config.ini')
print config.items('default_settings')
给
[('test','1')]
更新3.7
我最近一直在与configparser打交道并遇到过这篇文章。想我会用与3.7相关的信息来更新它。
例1:
config = configparser.ConfigParser(allow_no_value=True)
config.set('SECTION', '; This is a comment.', None)
例2:
config = configparser.ConfigParser(allow_no_value=True)
config['SECTION'] = {'; This is a comment':None, 'Option':'Value')
示例3:如果要保持字母大小写不变(默认是将所有选项:值对转换为小写)
config = configparser.ConfigParser(allow_no_value=True)
config.optionxform = str
config.set('SECTION', '; This Comment Will Keep Its Original Case', None)
“SECTION”是区分大小写的部分名称,您希望添加注释。使用“无”(无引号)而不是空字符串('')将允许您设置注释而不留下尾随“=”。
你也可以使用ConfigUpdater。它具有更多便利选项,可以以微创方式更新配置文件。
你基本上会这样做:
from configupdater import ConfigUpdater
updater = ConfigUpdater()
updater.add_section('DEFAULT')
updater.set('DEFAULT', 'test', 1)
updater['DEFAULT']['test'].add_before.comment('test comment', comment_prefix=';')
with open('./config.ini', 'w') as f:
updater.write(f)