0

I am trying to read .ini file with keywords having single items or list items. When I try to print single item strings and float values, it prints as h,e,l,l,o and 2, ., 1 respectively, whereas it should have been just hello and 2.1. Also, when I try to write new single item string/float/integer, there is , at the end. I am new to python and dealing with configobj. Any help is appreciated and if this question has been answered previously, please direct me to it. Thanks!

from configobj import ConfigObj

Read

config = ConfigObj('para_file.ini')
para = config['Parameters']
print(", ".join(para['name']))
print(", ".join(para['type']))
print(", ".join(para['value']))

Write

new_names = 'hello1'
para['name'] = [x.strip(' ') for x in new_names.split(",")]
new_types = '3.1'
para['type'] = [x.strip(' ') for x in new_types.split(",")]
new_values = '4'
para['value'] = [x.strip(' ') for x in new_values.split(",")]
config.write()

My para_file.ini looks like this,

[Parameters]

name = hello1
type = 2.1
value = 2
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
pyPN
  • 105
  • 3
  • 9
  • I'm quite confused by why you're expecting to get multiple values for any of your parameters. It looks to me like you only ever want to read one value for each name, and only intend to write one value as well. In that case, why not just do `print(para['name'])` and `para['name'] = new_names`? Is there some context where you *do* expect multiple values? – Blckknght Jan 19 '19 at 05:23
  • @Blckknght, thanks for your reply! Yes, I am trying to input the parameters to a GUI and the user config parameters can have either single item or list items. At the same time, user can modify the parameters and save it as either single item/list items. – pyPN Jan 19 '19 at 13:09

1 Answers1

0

There are two parts to your question.

  1. Options in ConfigObj can be either a string, or a list of strings.

    [Parameters]
      name = hello1             # This will be a string
      pets = Fluffy, Spot       # This will be a list with 2 items
      town = Bismark, ND        # This will also be a list of 2 items!!
      alt_town = "Bismark, ND"  # This will be a string
      opt1 = foo,               # This will be a list of 1 item (note the trailing comma)
    

    So, if you want something to appear as a list in ConfigObj, you must make sure it includes a comma. A list of one item must have a trailing comma.

  2. In Python, strings are iterable. So, even though they are not a list, they can be iterated over. That means in an expression like

    print(", ".join(para['name']))
    

    The string para['name'] will be iterated over, producing the list ['h', 'e', 'l', 'l', 'o', '1'], which Python dutifully joins together with spaces, producing

    h e l l o 1
    
TomK
  • 362
  • 2
  • 10