我有一个名为num_list.conf的配置文件
[SMART]
LIST={
'SMART' : {813,900,907,908,909,910,911,912,918,919,920,921,928,929,930,931,938,939,940,946,947,948,949,971,980,989,998,999}
}
[GLOBE]
LIST={
'GLOBE' : {817,905,906,915,916,917,926,927,935,936,937*,975,994,996,997},
'PREPAID' : {922,923,925,932,933,934,942,943,944}
}
[SUN_CELLULAR]
LIST=
'SUN_CELLULAR' : {922,923,925,932,933,934,942,943,944}
}
如何在python中读取这个字典类型
答案 0 :(得分:2)
我调用了你的文件num_list.conf并将其保存在D:中。你在其中一个数字中有一个星号,所以我不认为将数字转换为浮点或int是个好主意
这应该有效:
results = {}
with open(r'd:\num_list.conf') as conf:
for lines in conf:
if ":" in lines:
lineval = lines.split()
name = lineval[0].replace("'","")
numbers = lineval[-1][1:-1]
numbers = numbers.split(",")
results[name]=numbers
print(results)
#result
{'SMART': ['813', '900', '907', '908', '909', '910', '911', '912', '918', '919', '920', '921', '928', '929', '930', '931', '938', '939', '940', '946', '947', '948', '949', '971', '980', '989', '998', '999'], 'SUN_CELLULAR': ['922', '923', '925', '932', '933', '934', '942', '943', '944'], 'PREPAID': ['922', '923', '925', '932', '933', '934', '942', '943', '944'], 'GLOBE': ['817', '905', '906', '915', '916', '917', '926', '927', '935', '936', '937*', '975', '994', '996', '997}']}
答案 1 :(得分:0)
有一种更简单的方法。存在名为configparser的模块,但它不会自动转换为字典。相反,您可以将字典保存为json字符串并像这样加载它(您将不得不稍微更改配置文件的结构):
这是文件:
[SMART]
SMART = {"smart":[813,900,907,908,909,910,911,912,918,919,920,921,928,929,930,931,938,939,940,946,947,948,949,971,980,989,998,999]}
[GLOBE]
LIST={"GLOBE" : [817,905,906,915,916,917,926,927,935,936,937,975,994,996,997],"PREPAID" : [922,923,925,932,933,934,942,943,944]}
[SUN_CELLULAR]
LIST={"SUN_CELLULAR" : [922,923,925,932,933,934,942,943,944]}
这是python代码:
>>> import configparser
>>> import json
>>> conf = configparser.ConfigParser()
>>> conf.read("config.conf.txt")
['config.conf.txt']
>>> json.loads(conf["SMART"]["SMART"])
{'smart': [813, 900, 907, 908, 909, 910, 911, 912, 918, 919, 920, 921, 928, 929, 930, 931, 938, 939, 940, 946, 947, 948,
949, 971, 980, 989, 998, 999]}