[英]Read a comma separated INI file in python?
我有一個 INI 文件
[default]
hosts=030, 031, 032
我有逗號分隔的值。 我可以用一個簡單的方法讀取所有值
comma_separated_values=config['default']['hosts']
這樣我就可以獲得變量中的所有值。 但是我怎樣才能遍歷這個 INI 文件,以便我可以將所有這些值存儲為一個列表而不是變量。
假設這些值必須是整數,您可能希望在從逗號分隔的字符串中提取列表后將它們轉換為整數。
繼科爾文的回答之后:
values_list = [int(str_val) for str_val in config['default']['hosts'].split(',')]
或者,如果每個數字的零前綴應該表示它們是八進制:
values_list = [int(str_val, 8) for str_val in config['default']['hosts'].split(',')]
由於這些是作為字符串讀入的,因此您應該能夠執行此操作並將其存儲在列表中
values_list = config['default']['hosts'].split(',')
您可以將其概括如下:
import ConfigParser
import io
# Load the configuration file
def read_configFile():
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read("config.ini")
# List all contents
print("List all contents")
for section in config.sections():
#print("Section: %s" % section)
for options in config.options(section):
if (options == 'port'):
a = config.get(section,options).split(',')
for i in range(len(a)):
print("%s:::%s" % (options, a[i]))
else:
print("%s:::%s" % (options, config.get(section, options)))
read_configFile()
config.ini
[mysql]
host=localhost
user=root
passwd=my secret password
db=write-math
port=1,2,3,4,5
[other]
preprocessing_queue = ["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]
use_anonymous=yes
您可以讀取文件的內容並使用 split(',') 將其拆分。 嘗試使用下面的代碼。
with open('#INI FILE') as f:
lines = f.read().split(',')
print(lines) # Check your output
print (type(lines)) # Check the type [It will return a list]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.