21

So I'm writing a script that reads from a config file, and I want to use it exactly how configparser is designed to be used as outlined here: http://docs.python.org/release/3.2.1/library/configparser.html

I am using Python 3.2.1. The script, when complete, will run on a Windows 2008 R2 machine using the same version of Python, or assuming compatibility, the latest version at the time.

#!/user/bin/env python
import configparser

config = configparser.ConfigParser()
config.read('c:\exclude.ini')
config.sections()

That works fine to read the exclude.ini file - unless I have a value without a key. Thinking I might be doing something wrong tried parsing the example listed here: http://docs.python.org/release/3.2.1/library/configparser.html#supported-ini-file-structure

It still throws the following every time:

File "C:\Python32\lib\configparser.py", line 1081, in _read
    raise e
configparser.ParsingError: Source contains parsing errors: c:\exclude.ini
    [line 20]: 'key_without_value\n'

I'm at a loss... I'm literally copy/pasting the example code from the documentation for the exact python version I'm using and it's not working as it should. I can only assume I'm missing something as I also can't really find anyone with a similar issue.

Isxek
  • 1,096
  • 11
  • 19
Sparc
  • 287
  • 1
  • 3
  • 7

2 Answers2

32

The ConfigParser constructor has a keyword argument allow_no_value with a default value of False.

Try setting that to true, and I'm betting it'll work for you.

Karl Barker
  • 11,095
  • 3
  • 21
  • 26
  • 1
    Excellent, thankyou Karl. Perhaps I should send them a note suggesting changing their example .ini to put a comment above that section noting that part only works if the constructor is changed. I suppose I should have read the entire documentation, but the way things were set out it looked to me like it should have worked like this by default. – Sparc Feb 29 '12 at 00:32
  • This even works if the section looks like this: [Software] 3700 Journal Copy 1.0.2 Adobe Flash Player 11 ActiveX Adobe Reader X (10.1.7) - Deutsch DotNet Framework 4.0 [...] – enthus1ast Feb 10 '14 at 15:35
  • For more recent features of configparser, check the latest [python 3 docs](https://docs.python.org/3/library/configparser.html#configparser.ConfigParser). `allow_no_value` is still available. OP specified that (s)he uses python 3.2.1. – DanielTuzes Jun 22 '22 at 10:52
1
class RawConfigParser:
def __init__(self, defaults=None, dict_type=_default_dict,
             allow_no_value=False):
    self._dict = dict_type
    self._sections = self._dict()
    self._defaults = self._dict()
    if allow_no_value:
        self._optcre = self.OPTCRE_NV
    else:
        self._optcre = self.OPTCRE
    if defaults:
        for key, value in defaults.items():
            self._defaults[self.optionxform(key)] = value

import ConfigParser

cf = ConfigParser.ConfigParser(allow_no_value=True)

Jack Geller
  • 201
  • 1
  • 4