1

I'm not able to pass the values of a list to a for loop which will return the value assigned to it in config file at runtime.

My config file is demo.ini:

[DEMFILE]
Name='XYZABC'
Surname='TYUIO'
Code='123'
City='Kolkata'

I have a list in which I have parameters like below:

from configparser import ConfigParser
mylist=['Name','Code']
mylist_count=len(mylist)
   
dmfg=config_object["DEMFILE"]


for i in range(mylist_count):
    getValue=dmfg[i] # ---> Throws error 
    print(f'The value of {i} is : {getValue}')   

Expected Output for getValue is as shown below:

The value of Name is : XYZABC
The value of City is : Kolkata

I want whatever the values in list that should check in config file and return the output assigned to it.

For example: Name --> XYZABC (coming from config file).

ggorlen
  • 44,755
  • 7
  • 76
  • 106

1 Answers1

-1

You can create an instance of the ConfigParser, read the .ini file and use the key rather than its index to retrieve the value:

Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
>>> from configparser import ConfigParser
>>> config = ConfigParser()
>>> config.read("demo.ini")
['demo.ini']
>>> keys = ["Name", "Code"]
>>> vals = [config["DEMFILE"][x] for x in keys]
>>> vals
["'XYZABC'", "'123'"]

If the quotes seem odd, config values typically aren't quoted. Either remove the quotes from the config or strip them with [x[1:-1] for x in vals].

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • let me try your method –  Aug 18 '21 at 15:14
  • is it possible to get keys = [ ] initialise from file , my file as keys Name , City , Surname that should go into keys = [ Name , City , Surname ] –  Aug 18 '21 at 15:26
  • 1
    Yes that's possible. Store the list as a file in some format, say, an .ini file or one value per line and [read it into a list](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list). – ggorlen Aug 18 '21 at 15:29
  • i have a file in which cutting the column 3 which as Name surname city that i am trying to get into key with this command : `keys = [ x.split("|")[3].rstrip("\n") for x in open(dm.txt).readlines()]` this values when passed to `vals = [config["DEMFILE"][x] for x in keys]` it fails keyerror –  Aug 18 '21 at 15:38
  • Maybe ask a new question or try debugging it by printing each `x` with `repr(x)` to see what it contains exactly. There might be whitespace or a case issue. I'm not sure what `dm.txt` contains. It'd have to be in the format `a|b|c|Name` I'd think. If it's a CSV file, better to use a [CSV reader](https://docs.python.org/3/library/csv.html) rather than trying to parse it by hand. – ggorlen Aug 18 '21 at 15:39
  • I will post it as new question just check in few minutes –  Aug 18 '21 at 15:40
  • can you check this : https://stackoverflow.com/questions/68836171/how-to-use-list-values-into-config –  Aug 18 '21 at 16:34