2

The following is the file parsed by ConfigParser:

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

 4
 5

 7 

As described by the official Python wiki for ConfigParser examples, here is the helper function:

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

The resulting value is:

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

The expected value was:

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

4
5

7 

How do I fix this?

agf
  • 171,228
  • 44
  • 289
  • 238
paragbaxi
  • 3,965
  • 8
  • 44
  • 58

2 Answers2

1

Update: The link I gave you below was to Python 3.0, my apologies I forgot your tag.

The 2.7 docs do not mention blank lines in values, so I suspect they are not supported at all.

See also this SO question (which looks like Python 3): How to read multiline .properties file in python


From the documentation:

Values can also span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser’s mode, blank lines may be treated as parts of multiline values or ignored.

I don't know what 'parser mode' this is referring to, but not sure if what you want is doable.

On the other hand, the docs also mention the empty_lines_in_values option, which seems to indicate that blank lines are supported. Seems somewhat contradictory to me.

Community
  • 1
  • 1
jwd
  • 10,837
  • 3
  • 43
  • 67
  • Thanks for this, but as you already realized, I am using Python 2.7. There is no _empty_lines_in_values_ in ConfigParser for Python 2.7, unfortunately. – paragbaxi Oct 19 '11 at 23:10
  • @ghee22: If you are not restricted to the standard library, you could use ConfigObj, as mentioned in the SO link I gave. You can use triple-quotes to surround values. Here's the docs: http://www.voidspace.org.uk/python/configobj.html#the-config-file-format – jwd Oct 19 '11 at 23:17
0

One way to fix it is to modify the helper function to:

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
paragbaxi
  • 3,965
  • 8
  • 44
  • 58