Writing comments to files with ConfigParser
一个人如何在部分内将注释写入给定文件?
如果我有:
1 2 3 4 5 | import ConfigParser with open('./config.ini', 'w') as f: conf = ConfigParser.ConfigParser() conf.set('DEFAULT', 'test', 1) conf.write(f) |
我将得到文件:
1 2 | [DEFAULT] test = 1 |
但是如何获取
1 2 3 | [DEFAULT] ; test comment test = 1 |
我知道我可以通过以下方式向文件编写代码:
1 2 3 4 5 6 | 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有可能吗? 而且我不想尝试其他模块,因为我需要将程序保持为"库存"。
如果版本> = 2.7,则可以使用allow_no_value选项
此代码段:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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文件:
1 2 3 | [default_settings] ; comment here test = 1 |
您可以创建以#或;开头的变量。字符:
1 2 | conf.set('default_settings', '; comment here', '') conf.set('default_settings', 'test', 1) |
创建的conf文件是
1 2 3 | [default_settings] ; comment here = test = 1 |
ConfigParser.read函数不会解析第一个值
1 2 3 | config = ConfigParser.ConfigParser() config.read('config.ini') print config.items('default_settings') |
给
1 | [('test','1')] |
更新3.7
我最近一直在处理configparser,并遇到了这篇文章。我想用与3.7相关的信息来更新它。
范例1:
1 2 | config = configparser.ConfigParser(allow_no_value=True) config.set('SECTION', '; This is a comment.', None) |
范例2:
1 2 | config = configparser.ConfigParser(allow_no_value=True) config['SECTION'] = {'; This is a comment':None, 'Option':'Value') |
示例3:如果要保持字母大小写不变(默认是将所有option:value对转换为小写)
1 2 3 | config = configparser.ConfigParser(allow_no_value=True) config.optionxform = str config.set('SECTION', '; This Comment Will Keep Its Original Case', None) |
其中" SECTION"是要添加注释的区分大小写的节名称。使用"无"(不带引号)代替空字符串('')将使您可以设置注释,而无需在结尾加上" ="。
您也可以使用ConfigUpdater。它具有更多便捷选项,可以以最小的侵入方式更新配置文件。
您基本上会这样做:
1 2 3 4 5 6 7 8 | 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) |