2

以下是ConfigParser解析的文件:

[Ticket]
description = This is a multiline string.
 1
 2

 4
 5

 7 

正如ConfigParser 示例的官方 Python wiki 所述,这里是辅助函数:

def ConfigSectionMap(section):
    dict1 = {}
    options = Config.options(section)
    for option in options:
        try:
            dict1[option] = Config.get(section, option)
            if dict1[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1

结果值为:

>>> print ConfigSectionMap('Ticket')['description']
This is a multiline string.
1
2
4
5
7

预期值为:

>>> print ConfigSectionMap('Ticket')['description']
This is a multiline string.
1
2

4
5

7 

我该如何解决?

4

2 回答 2

1

更新:我在下面给你的链接是 Python 3.0,很抱歉我忘记了你的标签。

2.7 文档没有提到值中的空行,所以我怀疑它们根本不受支持。

另请参阅这个 SO 问题(看起来像 Python 3):How to read multiline .properties file in python


文档中:

值也可以跨越多行,只要它们的缩进比值的第一行更深。根据解析器的模式,空行可能被视为多行值的一部分或被忽略。

我不知道这是指什么“解析器模式”,但不确定您想要的是否可行。

另一方面,文档还提到了该empty_lines_in_values选项,这似乎表明支持空。对我来说似乎有些矛盾。

于 2011-10-19T22:51:58.683 回答
0

修复它的一种方法是将辅助函数修改为:

def ConfigSectionMap(section):
    dict1 = {}
    options = Config.options(section)
    for option in options:
        try:
            dict1[option] = Config.get(section, option).replace('\\n', '')
            if dict1[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1
于 2011-10-19T23:19:07.673 回答