[英]Issue with Configobj-python and list items
I am trying to read .ini
file with keywords having single items or list items. 我正在尝试使用具有单个项目或列表项目的关键字来读取
.ini
文件。 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
. 当我尝试打印单个项目字符串和浮点值时,它分别打印为
h,e,l,l,o
和2, ., 1
,而应该只是hello
和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
. 我是python和
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, 我的
para_file.ini
看起来像这样,
[Parameters]
name = hello1
type = 2.1
value = 2
There are two parts to your question. 您的问题分为两部分。
Options in ConfigObj can be either a string, or a list of strings. ConfigObj中的选项可以是字符串,也可以是字符串列表。
[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. 因此,如果您希望某些内容在ConfigObj中显示为列表,则必须确保它包含逗号。 A list of one item must have a trailing comma.
一项的列表必须带有逗号结尾。
In Python, strings are iterable. 在Python中,字符串是可迭代的。 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 字符串
para['name']
将被遍历,产生列表['h', 'e', 'l', 'l', 'o', '1']
,Python会尽职地将其与空格连接在一起,生产
hello 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.