python-3.x - Python 3 ConfigParser 也读取内联注释

标签 python-3.x parsing config configparser

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

结果的一些行:

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)))

最佳答案

默认情况下不启用内联注释 .

来自 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.

允许使用 ';' 进行内嵌评论:
parser = configparser.ConfigParser(inline_comment_prefixes=';')

关于python-3.x - Python 3 ConfigParser 也读取内联注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896839/

相关文章:

python - 使用正则表达式从字符串中提取所有电子邮件

c++ - stringstream >> 不一致的 '\n' 定界符行为

namespaces - 按模式查找 hiera 配置

java - 使用依赖注入(inject)连接多个配置类

python-3.x - 如何使 dateparser 解析相对于给定日期的日期

python追加2d列表不能按预期工作,这是一个错误吗?

python - Python 文档中@classmethod 的参数的作用是什么?

c# - C# 是否内置支持解析页码字符串?

html - 如何将 HTML 表中的数据解析为 Julia 数据结构

linux - bash 脚本没有在 nohup 中运行,但可以独立运行