简体   繁体   中英

Issue with Configobj-python and list items

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

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

     hello 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM