基于ConfigParser模块,如何过滤掉ini文件并抛出每个注释?
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("sample.cfg")
for section in config.sections():
print section
for option in config.options(section):
print option, "=", config.get(section, option)
例如。在上面基本脚本下面的ini文件中打印出更多注释行,如:
something = 128 ; comment line1
; further comments
; one more line comment
我需要的是只有部分名称和纯键值对,而没有任何注释。 ConfigParser是以某种方式处理此问题还是应该使用regexp ...或?干杯
答案 0 :(得分:5)
根据以;
或#
开头的docs行将被忽略。您的格式似乎不满足该要求。您可以通过任何机会更改输入文件的格式吗?
编辑:由于您无法修改输入文件,我建议您使用以下内容对其进行预解析:
tmp_fname = 'config.tmp'
with open(config_file) as old_file:
with open(tmp_fname, 'w') as tmp_file:
tmp_file.writelines(i.replace(';', '\n;') for i in old_lines.readlines())
# then use tmp_fname with ConfigParser
显然,如果选项中存在分号,您必须更具创造性。
答案 1 :(得分:3)
最好的方法是编写一个无评论的file
子类:
class CommentlessFile(file):
def readline(self):
line = super(CommentlessFile, self).readline()
if line:
line = line.split(';', 1)[0].strip()
return line + '\n'
else:
return ''
您可以使用它与configparser(您的代码):
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(CommentlessFile("sample.cfg"))
for section in config.sections():
print section
for option in config.options(section):
print option, "=", config.get(section, option)
答案 2 :(得分:2)
您的评论似乎不在开始与评论领导者的行上。如果评论标题是该行的第一个字符,它应该有效。
答案 3 :(得分:1)
正如文档所说:“(仅用于向后兼容;启动内联注释,而#不启用。)”所以使用“;”内联评论不是“#”。它对我很有用。
答案 4 :(得分:0)
Python 3附带了一个内置解决方案:类configparser.RawConfigParser具有构造函数参数inline_comment_prefixes
。例如:
class MyConfigParser(configparser.RawConfigParser):
def __init__(self):
configparser.RawConfigParser.__init__(self, inline_comment_prefixes=('#', ';'))