Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to use the following .ini file 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 a call to read() dumps 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'

My understanding is that the expected format is key = value (a value is required).

My questions:

  • is ConfigParser usable for such files?
  • if not: is there a good alternative to parse similar files?

I can reformat the config file but would like to keep a simple, raw list of entries per section -- as opposed to faking the key = value format with something like range1 = 192.168.1.0/24

like image 602
WoJ Avatar asked Nov 14 '13 07:11

WoJ


People also ask

How parse config file in Python?

The configparser module has ConfigParser class. It is responsible for parsing a list of configuration files, and managing the parsed database. Return all the configuration section names. Return whether the given section exists.

How do you create and read config file in Python?

Python can have config files with all settings needed by the application dynamically or periodically. Python config files have the extension as . ini. We'll use VS Code (Visual Studio Code) to create a main method that uses config file to read the configurations and then print on the console.


1 Answers

Use allow_no_value parameter:

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

According to ConfigParser.RawConfigParser (base class of ConfigParser):

When allow_no_value is true (default: False), options without values are accepted; the value presented for these is None.

NOTE: available in Python 2.7+, 3.2+

like image 155
falsetru Avatar answered Oct 20 '22 07:10

falsetru