2

I have an INI windows file with the following format:

[STRINGS]
property 1 = "hello"
property 2 = ""
PROPERTY 3 = ""

but if I get values using ConfigParser

init_values= ConfigParser.RawConfigParser(allow_no_value=True)
init_values.optionxform = str
init_values.read(init_file)

and modify one of them (p.e. property 1)

init_values.set('STRINGS', 'property 1', '"world"')
init_values.write(configfile)

I get the following result:

[STRINGS]
property 1 = "world"
property 2 = 
PROPERTY 3 = 

All the quotes from empty values are removed.

How can I force to use quotes even in empty values?

togarha
  • 163
  • 3
  • 12

2 Answers2

1
init_values.set('STRINGS', 'property 1', '"world"')

If you look at what you are doing here, you are explicitly adding quotes to the value. If you were to remove the quotes around world, you would just get the following output:

[STRINGS]
property 1 = world
property 2 =
property 3 =

That is because INI files don’t actually use quotes to signalize string values (since every value is a string).

What may be a problem though is that the parser explicitly recognizes "" as an empty string value and replaces it by the empty string, while quotes around other values are kept as they are. This is a built-in behavior of the 2.7 parser and cannot really be changed without implementing it yourself.

Note that in Python 3, this behavior was changed, so "" is being recognized as the string '""'.

poke
  • 369,085
  • 72
  • 557
  • 602
0

Let's take have an INI windows file with the following format:

[STRINGS]
property 1 = "hello"
property 2 = ""
PROPERTY 3 = ""

You can do it by following way. For example:

import ConfigParser

filename='config'
parser=ConfigParser.SafeConfigParser()
parser.read([filename])
print(parser.sections())
# ['section']
for section in parser.sections():
    print(parser.options(section))
    # ['id', 'rb', 'person']
    for option in parser.options(section):
        try:
            value=parser.getint(section,option)
        except ValueError:
            value=parser.get(section,option)
        print(option,value,type(value))
print(parser.items('section'))
# [('property1', 'world'), ('property2', ''), ('property3', '')]