【问题标题】:Python 3 ConfigParser reading the inline comments as wellPython 3 ConfigParser 也读取内联注释
【发布时间】:2016-10-06 13:06:06
【问题描述】:

我有以下代码,其中filePath 是磁盘上cfg 文件的路径。当我解析它时,它还会读取内联 cmets(带有空格的 cmets + ";")。

结果的几行:

xlsx:是的;评论放在这里

html:是的;评论放在这里

应该是:

xlsx:是的

html:是的

def ParseFile(filePath):
    """this function returns the parsed CFG file"""
    parser = configparser.ConfigParser()
    print("Reading config file from %s" % filePath)
    parser.read(filePath)
    for section in parser.sections():
        print("[ SECTION: %s ]" % section)
        for option in parser.options(section):
            print("%s:%s" % (option, parser.get(section, option)))

【问题讨论】:

    标签: python-3.x parsing config configparser


    【解决方案1】:

    默认情况下不启用内联 cmets

    来自the docs中的一个例子:

    [You can use comments]
    # like this
    ; or this
    
    # By default only in an empty line.
    # Inline comments can be harmful because they prevent users
    # from using the delimiting characters as parts of values.
    # That being said, this can be customized.
    

    允许使用 ';' 的内联 cmets:

    parser = configparser.ConfigParser(inline_comment_prefixes=';')
    

    【讨论】:

      猜你喜欢
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多