Python: how to read configuration file with only keys (no values)

I would like to use the following .inifile with ConfigParser.

[Site1]
192.168.1.0/24
192.168.2.0/24

[Site2]
192.168.3.0/24
192.168.4.0/24

Unfortunately, the call read()throws the following error:

import ConfigParser
c = ConfigParser.ConfigParser()
c.read("test.ini")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\ConfigParser.py", line 305, in read
    self._read(fp, filename)
  File "C:\Python27\lib\ConfigParser.py", line 546, in _read
    raise e
ConfigParser.ParsingError: File contains parsing errors: test.ini
        [line  2]: '192.168.1.0/24\n'
        [line  3]: '192.168.2.0/24\n'
        [line  6]: '192.168.3.0/24\n'
        [line  7]: '192.168.4.0/24\n'

I understand the expected format key = value(required).

My questions:

  • ConfigParser can be used for such files?
  • if not: is there a good alternative for parsing such files?

I can reformat the configuration file, but would like to keep a simple, raw list of entries in the section - as opposed to falsifying the format key = valuewith something likerange1 = 192.168.1.0/24

+4
source share
3 answers

Use option allow_no_value:

import ConfigParser
c = ConfigParser.ConfigParser(allow_no_value=True)
c.read("test.ini")

ConfigParser.RawConfigParser ( ConfigParser):

allow_no_value ( : False), ; , , .

: Python 2.7+, 3.2 +

+8

allow_no_value True

import ConfigParser
c = ConfigParser.ConfigParser(allow_no_value=True)
c.read("test.ini")

ConfigObj .

-1

Your ini file is not valid. You can use JSON style formatting:

{
    "site1": ["192.168.1.0/24", "192.168.2.0/24"],
    "site2": ["192.168.3.0/24", "192.168.4.0/24"]
}

Then use the python json library.

>>> import json
>>> with open("hello.json") as f:
    ...    foo = f.read()
    ...    a = json.loads(foo)
    ...
>>> a
    {'site2': ['192.168.3.0/24', '192.168.4.0/24'], 'site1': ['192.168.1.0/24', '192.168.2.0/24']}
-3
source

All Articles