是否有一个解析器可以读取和存储要写入的数据类型?文件格式必须产生可读性。搁置不提供。
问问题
3037 次
3 回答
1
使用ConfigParser
类读取ini文件格式的配置文件:
http://docs.python.org/library/configparser.html#examples
ini 文件格式不存储所存储值的数据类型(您在读回数据时需要知道它们)。您可以通过将值编码为 json 格式来克服此限制:
import simplejson
from ConfigParser import ConfigParser
parser = ConfigParser()
parser.read('example.cfg')
value = 123
#or value = True
#or value = 'Test'
#Write any data to 'Section1->Foo' in the file:
parser.set('Section1', 'foo', simplejson.dumps(value))
#Now you can close the parser and start again...
#Retrieve the value from the file:
out_value = simplejson.loads(parser.get('Section1', 'foo'))
#It will match the input in both datatype and value:
value === out_value
作为 json,存储值的格式是人类可读的。
于 2011-06-19T13:57:24.020 回答
0
您可以使用以下功能
def getvalue(parser, section, option):
try:
return parser.getint(section, option)
except ValueError:
pass
try:
return parser.getfloat(section, option)
except ValueError:
pass
try:
return parser.getbool(section, option)
except ValueError:
pass
return parser.get(section, option)
于 2011-06-19T14:33:40.703 回答
0
有了configobj
图书馆,它变得非常简单。
import sys
import json
from configobj import ConfigObj
if(len(sys.argv) < 2):
print "USAGE: pass ini file as argument"
sys.exit(-1)
config = sys.argv[1]
config = ConfigObj(config)
现在您可以config
用作 dict 来提取所需的配置。
如果你想把它转换成json
,那也很简单。
config_json = json.dumps(config)
print config_json
于 2017-08-09T07:05:19.440 回答