Search code examples
pythonconfigparser

How to read all words under a section in configparser?


I'm reading from a file which has a section structured like this:

[name]
John
Mary
Ben
John

Note that there are no keys.

How to read those values with ConfigParser?

Thanks


Solution

  • You should create your ConfigParser with the keyword argument allow_no_value set to True. Also you need to remove the duplication in your file (John appears twice).

    config = configparser.ConfigParser(allow_no_value=True)
    config.read("config_file_name")
    
    for name in config["name"]:
        print(name)
    

    Output:

    John
    Mary
    Ben
    

    If you need the duplications in the name section, you will have to inherit the ConfigParser class and override that limitation.


    Side note:

    Consider using a JSON or YAML instead of an ini file for such task, it will make your life much easier