Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing configure file with same section name in python

I try to parse file like:

[account]
User = first

[account]
User = second

I use ConfigParser in Python, but when i read file:

Config = configparser.ConfigParser()
Config.read(file)
print (Config.sections())

I have error:

While reading from ... : section 'account' already exists

How can i parse this file? Are any another library? (prefer for python3)

like image 889
ExyTab Avatar asked Mar 26 '12 16:03

ExyTab


People also ask

How do you configure a 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.

What is ConfigParser ConfigParser ()?

ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.

What is config () in Python?

A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a Config instance.


1 Answers

If what you want is to simply merge identically named sections (latest one wins), simply pass the strict=False option to the constructor (added in Python 3.2). You effectively get dict.update() behavior as the duplicate sections are merged in.

Config = configparser.ConfigParser(strict=False)

However, it's clear from the OP's sample data that identically named sections need to be kept separate, to avoid loss of data. ConfigParser stores the sections it reads in a dictionary, so it can't handle multiple sections with the same name. Fortunately the constructor accepts a dict_type argument that allows you to specify a different dictionary-like object. You can use that to support identically named sections. Here's a crude solution that mangles the section names by appending a unique number whenever a section name has been seen before.

from collections import OrderedDict

class multidict(OrderedDict):
    _unique = 0   # class variable

    def __setitem__(self, key, val):
        if isinstance(val, dict):
            self._unique += 1
            key += str(self._unique)
        OrderedDict.__setitem__(self, key, val)

Config = configparser.ConfigParser(defaults=None, dict_type=multidict, strict=False)

With a little work you should be able to construct a cleaner solution.

like image 156
alexis Avatar answered Sep 23 '22 21:09

alexis