我有一個ini文件在python中讀取逗號分隔的ini文件?
[default]
hosts=030, 031, 032
其中我有一個逗號分隔值。我可以用一個簡單的值讀取整個值
comma_separated_values=config['default']['hosts']
這樣我就可以得到變量中的所有值。但是,我怎樣才能遍歷這個INI文件,以便我可以將所有這些值存儲爲列表而非變量。
我有一個ini文件在python中讀取逗號分隔的ini文件?
[default]
hosts=030, 031, 032
其中我有一個逗號分隔值。我可以用一個簡單的值讀取整個值
comma_separated_values=config['default']['hosts']
這樣我就可以得到變量中的所有值。但是,我怎樣才能遍歷這個INI文件,以便我可以將所有這些值存儲爲列表而非變量。
假設這些值必須是整數,您需要在從逗號分隔的字符串中提取列表後,將它們轉換爲整數。
從Colwin的回答繼:
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(',')]
謝謝@David,上面的答案正是我在尋找的......當我讀取INI文件時,它被存儲爲一個unicode類型,但是你的代碼幫助我將它們存儲爲int並且也作爲列表存儲。 謝謝你的幫助。 – Rob
由於這些越來越閱讀作爲一個字符串,你應該能夠做到這一點,並將其存儲在一個列表
values_list = config['default']['hosts'].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]
海報表明他們可以通過config ['default'] ['hosts']'訪問逗號分隔值的字符串。這表明他們已經解析了INI文件(可能使用了類似於'ConfigParser'模塊的東西),並且它試圖通過'file.read()'函數將文件解析爲無格式文本是一個倒退的主要步驟。 –
可以按照如下概括它:
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
[在配置文件中迭代部分]的可能重複(https://stackoverflow.com/questions/220 68050/iterate-over-sections-in-a-config-file) – Martin