【发布时间】:2015-07-31 13:08:24
【问题描述】:
我正在使用 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'}]}
所以我猜这是因为我在配置文件中使用了制表符和空格。但我需要在配置文件中美化,因为用户会更新它。
我也试过asteval 和json.load。 T.I.A.
【问题讨论】:
标签: python json runtime-error config python-3.4