基于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...or?干杯
发布于 2009-02-19 10:36:28
根据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显然,如果分号出现在选项中,你就必须更有创造性。
发布于 2009-02-19 13:38:19
最好的方法是编写一个无注释的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)发布于 2009-02-19 11:40:31
你的评论似乎不在以评论开头的行上。如果注释前导是行中的第一个字符,它应该可以工作。
https://stackoverflow.com/questions/564662
复制相似问题