0

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?

borisbn
  • 4,988
  • 25
  • 42
bazyl
  • 263
  • 1
  • 7
  • 17
  • You can split values apart using `a, b = str.split()`. However, if you have mixed `(` and `{` entries as shown in your example, a regular expression may be more suitable. – ti7 Aug 05 '16 at 08:22
  • So, you receommed to use some function directly on strings ? Is it the best aproach? Maybe I could write my configini.file in different way to easier get that values? – bazyl Aug 05 '16 at 08:26
  • @ti7, Okay then I will use split function, but how to assign value after comma to other variable ? – bazyl Aug 05 '16 at 08:31

2 Answers2

1

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

Trimax
  • 2,413
  • 7
  • 35
  • 59
1

Yet another way:

ConfigParser.ini

[Filenames]
Table1.filename=logs.table2
Table1.filenumber=92
Table2.filename=logs.table2
Table2.filenumber=91
Table3.filename=audit.table3
Table3.filenumber=34
Table4.filename=audit.table4
Table4.filenumber=85

Code:

from configparser import ConfigParser
config = ConfigParser()
config.read('ConfigParser.ini')
print config.get('Filenames', 'Table1.filename')
print config.get('Filenames','Table1.filenumber')
tianwei
  • 1,859
  • 1
  • 15
  • 24