Search code examples
pythonconfigparser

separation of the string in .ini file (configparser)


My ConfigParser.ini file looks like:

[Filenames]
Table1={"logs.table2",92}
Table2=("logs.table2",91)
Table3=("audit.table3",34)
Table4=("audit.table4",85)

and now for example for Table1, I would like to get "logs.table2" value and 92 as separate variables.

import configparser
filename=config.get('FIlenames','Table1')

As result I would like to get:

print(filename) -> logs.table2
print(filenumber) -> 92

For now output is just a string ""logs.table2",92". Truly I have no idea how to handle that, maybe I should modify my config file? What is the best aproach?


Solution

  • Parsing .ini files is getting strings.

    [Filenames]

    Table1=logs.table2,92

    Table2=logs.table2,91

    Table3=audit.table3,34

    Table4=audit.table4,85

    table is a string, so you can split its contents into a list of comma separated values

    import configparser
    config = configparser.ConfigParser()
    config.read('config.ini')
    table=config.get('Filenames','Table1')
    list_table = table.split(',')
    print(list_table[0])
    print(list_table[1])
    

    But, best practise is to put in separated lines all the name=value pairs:

    [Filenames]

    TABLE1_FILENAME = logs.table2

    TABLE1_FILENUMBER = 92