簡體   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