Search code examples
pythonconfigwhitespaceini

Whitespace as a value in .ini file


I want my .ini file to have an option to specify a certain character as a splitter for the parameters which is then handled with Python. That is:

[meta]
split_char = " "

[stuff]
field = value_1 value_2

How can I specify a whitespace as a split char so it is recognizable? I have tried " " or [ ] and some other oprions, neither of them works.

As I've been asked, here is the Python scripts to read the .ini file:

from configparser import ConfigParser

config = ConfigParser()
config.read('config.ini')

# I need a nested dictionary, but this is not the point
split_char = config["meta"]["split_char"]
config = {section: dict(config.items(section)) for section in config.sections() if section != "meta"}
for section in config:
    for parameter in config[section]:
        config[section][parameter] = config[section][parameter].split(split_char)

If I place a whitespace as it is, Python considers the splitter empty, adding quotes or any other auxiliary signs does not get the things done.

Update

The thing is that I would also like to be able to require splitters like ', ', which is a string with a whitespace.


Solution

  • This can be done with a trickery like:

    split_char = config["meta"]["split_char"][1:-1]
    

    Then the splitter can be placed inside quotes or brackets or whatever:

    [meta]
    split_char = " "
    

    The amount of characters to split does not matter as well, it's easy to go with things like , .