gpt4 book ai didi

python - 如何在python中读取json嵌入ini配置文件

转载 作者:行者123 更新时间:2023-12-01 04:35:46 26 4
gpt4 key购买 nike

我正在使用 python 3.4,我在以格式化方式读取具有 json 格式的配置文件时遇到问题(即不在同一行中。)我的配置文件“Example.config”如下所示

[ABC]

outdoor = {'GAME':['cricket',
'football'],
'INFO':[
{'Players':'eleven',
'Fun':'Unlimited'},
{'Players':'something',
'Fun':'Much_more'}
]
}

[XYZ]

INDOOR = {'GAME':['Carom'],
'INFO':[
{'Players':'2','Fun':'Less'},
{'Players':'4','Fun':'More'}
]
}

INDOOR1 = {'GAME':['TABLE-TENNIS',
'BASKETBALL',
'ANYTHING'],
'INFO':[
{'Players':'TWO','Fun':'MORE'},
{'Players':'MORE','Fun':'MUCHMORE'}
]
}

我的代码

config_parser=ConfigParser()
config_parser.read('Example.config')
for each_section in config_parser.sections():
for option in config_parser.options(each_section):
option=ast.literal_eval(option)
try:
games=option['GAME']
info=option['INFO']
except:
print('PLease format config same as qa_config.config file.Please Pay special attention to casing')
raise

for game in games:
for eachInfo in info:
_INFO=eachInfo['Players']
_FUN=eachInfo['Fun']
print (each_section,':\n')
print ('\t',game,':\n')
print ('\t',_INFO,':\n')
print ('\t',_FUN,':\n')

错误:

option=ast.literal_eval(option)
File "C:\Python34\lib\ast.py", line 84, in literal_eval
return _convert(node_or_string)
File "C:\Python34\lib\ast.py", line 83, in _convert
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x02E61910>

如果我将字典作为字符串保留在一行中,而不在配置文件中进行任何美化 ast.literal_eval() 就能够处理它。

例如:

outdoor = {'GAME':['cricket','football'],'INFO':[{'Players':'eleven','Fun':'Unlimited'},{'Players':'something','Fun':'Much_more'}]}

所以我猜这是由于我在配置文件中使用的制表符和空格造成的。但我需要美化配置文件,因为用户会更新它。

我还尝试过 astevaljson.load。 T.I.A.

最佳答案

我尝试了你的代码和示例(诚然在 2.7 中)和问题是您在错误的事情上使用了 ast.literal_eval()

您在选项上使用它,这是左侧的名称ini 文件(在您的示例中为“outdoor”、“INDOOR”和“INDOOR1”)。您想在此选项的右侧使用它。

将下面缺少的第二行添加到脚本中的相应循环中:

    for option in config_parser.options(each_section):
option = config_parser.get(each_section, option)
option = ast.literal_eval(option)

您的多行 ini 文件已完美解析。

关于python - 如何在python中读取json嵌入ini配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31746977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com