繁体   English   中英

Python 2.x-ConfigParser在多行值中剥离空白行

[英]Python 2.x - ConfigParser stripping blank lines in multiline value

以下是ConfigParser解析的文件:

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

 4
 5

 7 

官方Python Wiki上针对ConfigParser示例所描述的,以下是辅助函数:

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 

我该如何解决?

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

2.7文档没有在值中提及空行,因此我怀疑根本不支持它们。

另请参见此SO问题(看起来像Python 3): 如何在python中读取多行.properties文件


文档中

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

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

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

解决该问题的一种方法是将辅助函数修改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM