書き込むデータの種類を読み取って保存するパーサーはありますか?ファイル形式は、読み取り可能なものを生成する必要があります。棚は提供していません。
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 に答える