1

as one knows, the ConfigParser from Python is designed for working with the old nt-style *.ini files from Microsoft. Anyway, it seems to be an not unusual case to use the ConfigParser for *.properties files as well, as they have a similar structure to the ini ones.

In my use-case, I want to parse a properties-file which works fine manually adding a dummy-section and then editing/reading the attributes. Anyway, I am currently searching for a solution of how to update the file without the section included. I.e. configparser.write() generates a file similar to the following lines:

[root]
a1 = v1 
a2 = v2
...

In order to use the file lateron it is needed to remove the dummysection line. This could be done removing the first line of the file, but I was hoping that anyone would know a better solution taking advantage of configparser methods. Thanks in advance.

schneiti
  • 428
  • 1
  • 8
  • 22
  • Have you tried using .items routine for ConfigParser and creating a dictionary for each section. The `mydict = dict(ConfigParser.items(section))` code will return a dictionary for each section if that what you want – cmidi Jan 30 '15 at 15:27
  • thanks for the idea, but actually this is not what I am looking for. All I want is a configparser that can deal .properties files without any sections at all. The workaround with a dummysection is fine but after editing the configuration values the file has to be restored the original grammar that it used to be before. in expression, the [root] shall be missing in the saved file! – schneiti Jan 30 '15 at 16:06
  • oh I understood it otherwise in that case it is a possible duplicate of [parsing .properties file in Python](http://stackoverflow.com/questions/2819696/parsing-properties-file-in-python) – cmidi Jan 30 '15 at 16:18

1 Answers1

0

ConfigParser object has a list of methods that can be used collectively to return the values of the config elements per section. The following code below can be used to convert the config elements of a particular section to a dictionary for later use.

import ConfigParser
config = ConfigParser.ConfigParser()
rc = config.read('test.properties')
sectionList = config.sections()
if 'root' in sectionList:
    elemDict = dict(config.items('root'))

The ConfigParser manual page has more information about this. The following page is for python 3.3.

https://docs.python.org/3.3/library/configparser.html#ConfigParser.RawConfigParser

cmidi
  • 1,880
  • 3
  • 20
  • 35