0

I have seen a lot of answers on how to read in a list using ConfigParser in Python:

But I am wondering how I can read in a list with multiple lists

For example, I have a config.ini:

[INPUT]
values = [[40000, 60000], [70000, 80000]]

A function in my main.py needs to read the above as:

[[40000, 60000], [70000, 80000]]

I am not sure if it matters, but values can be any size list, so for example:

[[40000, 60000]]

or

[[40000, 60000], [70000, 80000], [90000, 95000]]

I know the below will not work, but for clarity, I am reading the lists within the list into main.py like this:

self.values = config['INPUT']['values']

self is there because I am using a class. These are my declarations in the beginning of main.py:

import configparser
config = configparser.ConfigParser()
config.sections()
config.read('config.ini')
W. Churchill
  • 346
  • 1
  • 7
  • 28

1 Answers1

2

You can store a list (or list of lists or dict or whatever) as a string, and use ast to recover it.

Config:

[INPUT]
values = [[40000, 60000], [70000, 80000]]

And script (simplified as reading string variable from config is not a problem):

import ast
list_in_list = ast.literal_eval(string_var_read_from_config)
Grzegorz Pudłowski
  • 477
  • 1
  • 7
  • 14
  • I formatted my config file to read in `values` as a string like the one you mentioned in your answer, would I now read it into my main.py as follows? `self.values = ast.literal_eval(['INPUT']['values'])`, if I run this I get "TypeError: list indices must be integers or slices, not str". I need the numbers within the lists to be read as integers. – W. Churchill Apr 11 '20 at 09:03
  • No, you forgot that your values are stored in `config` object so `self.values = ast.literal_eval(config['INPUT']['values'])` – Grzegorz Pudłowski Apr 12 '20 at 02:37
  • Thank you, your solution using `import ast` worked. But I noticed that the way it worked for me was by not making `values` in my config file a string. `values = '[[40000, 60000], [70000, 80000]]'` did not work for me because the numbers inside the list were still being imported as strings, however, putting `values = [[40000, 60000], [70000, 80000]]` in my config file did work. Not sure why this was the case, but maybe you might be able to elaborate on it. – W. Churchill Apr 14 '20 at 06:23
  • 1
    I corrected myself. Config parser reads this value as a string by default. If you add quotation marks then it reads string with quotation marks in it. The `ast` module should recognize it as string and it did. So... no quotation marks. – Grzegorz Pudłowski Apr 15 '20 at 08:45