【问题标题】:Python - ConfigParser throwing commentsPython - ConfigParser 抛出评论
【发布时间】:2009-02-19 10:27:21
【问题描述】:

基于 ConfigParser 模块如何过滤并抛出 ini 文件中的每个 cmets?

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 文件中,打印出进一步的 cmets 行,例如:

something  = 128     ; comment line1
                      ; further comments 
                       ; one more line comment

我需要的是里面只有部分名称和纯键值对,没有任何 cmets。 ConfigParser 是否以某种方式处理这个问题,或者我应该使用正则表达式......还是?干杯

【问题讨论】:

  • “扔掉”是什么意思?请明确说明您真正想要做什么——为什么需要从文件中“丢弃”数据?它去哪儿了?留下了什么?

标签: python configparser


【解决方案1】:

根据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

显然,如果分号出现在选项中,您就必须更有创意。

【讨论】:

    【解决方案2】:

    最好的办法是写一个无注释的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)
    

    【讨论】:

    • 我觉得这里有一个小错字,应该是super(CommentlessFile, self).readline(),而不是CommentRemover。
    • @sykora:我在第一篇帖子后 5 秒修复了 :)
    【解决方案3】:

    您的 cmets 似乎不在以评论领导者开始的行上。如果评论领导者是该行的第一个字符,它应该可以工作。

    【讨论】:

    • 谢谢,但不幸的是,我不允许修改输入的 ini 文件。在这种 ini 文件格式中,我注意到所有注释行都附加到最后一个键的值部分 - 除了第一个注释确实被删除的行(在值之后)。
    • 其实我的任务是比较两个ini文件(除了cmets每个重要部分)
    • 那么您可能必须创建一个临时文件和/或使用 ConfigParser.readfp() 来报废 cmets。
    【解决方案4】:

    正如文档所说:“(为了向后兼容,只有 ; 开始一个内联注释,而 # 没有。)”所以使用“;”而不是 "#" 用于内联 cmets。对我来说效果很好。

    【讨论】:

      【解决方案5】:

      Python 3 自带一个内置解决方案:configparser.RawConfigParser 类具有构造函数参数inline_comment_prefixes。示例:

      class MyConfigParser(configparser.RawConfigParser):
          def __init__(self):
            configparser.RawConfigParser.__init__(self, inline_comment_prefixes=('#', ';'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-01
        • 2013-01-22
        • 2011-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 1970-01-01
        相关资源
        最近更新 更多