繁体   English   中英

Configobj-python和列表项出现问题

[英]Issue with Configobj-python and list items

我正在尝试使用具有单个项目或列表项目的关键字来读取.ini文件。 当我尝试打印单个项目字符串和浮点值时,它分别打印为h,e,l,l,o2, ., 1 ,而应该只是hello2.1 此外,当我尝试写新的单个项目串/浮点/整数,有,在年底。 我是python和configobj 感谢您的帮助,如果以前已回答过此问题,请直接向我提出。 谢谢!

from configobj import ConfigObj

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

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()

我的para_file.ini看起来像这样,

[Parameters]

name = hello1
type = 2.1
value = 2

您的问题分为两部分。

  1. 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) 

    因此,如果您希望某些内容在ConfigObj中显示为列表,则必须确保它包含逗号。 一项的列表必须带有逗号结尾。

  2. 在Python中,字符串是可迭代的。 因此,即使它们不是列表,也可以对其进行迭代。 这意味着像

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

    字符串para['name']将被遍历,产生列表['h', 'e', 'l', 'l', 'o', '1'] ,Python会尽职地将其与空格连接在一起,生产

     hello 1 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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