0

我正在尝试.ini使用具有单个项目或列表项的关键字读取文件。当我尝试打印单个项目字符串和浮点值时,它分别打印为h,e,l,l,oand 2, ., 1,而它应该只是helloand 2.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
4

1 回答 1

0

你的问题有两个部分。

  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']将被迭代,产生 list ['h', 'e', 'l', 'l', 'o', '1'],Python 尽职尽责地与空格连接在一起,产生

    h e l l o 1
    
于 2019-02-19T21:38:51.317 回答