【发布时间】:2018-07-16 21:21:48
【问题描述】:
我已将字典保存为 txt 文件为
f = open("dict_imageData.txt","a")
f.write( str(dict_imageData) + "\n" )
f.close()
并且保存的txt文件包含
{'002_S_0559': array([ 0., 0., 0., ..., 0., 0., 0.],dtype=float32)}
{'002_S_1070': array([ 0., 0., 0., ..., 0., 0., 0.], dtype=float32)}
{'023_S_0604': array([ 0., 0., 0., ..., 0., 0., 0.], dtype=float32)}
我在加载此字典和拆分键和值时遇到问题。我尝试了拆分和 eval 但没有奏效,因为最后有一个 dtype 语句。
有什么建议吗?
【问题讨论】:
-
是的,我建议您不要简单地将字典的字符串表示形式转储到文本文件中并自行编写您自己的序列化格式,而是依赖于其中之一现有的许多标准,即 JSON、基于文本的 YAML、用于二进制的
pickle。由于您正在使用numpy,因此可能最好使用numpy特定格式,使用numpy.save或numpy.savez用于多个命名数组... -
注意:
eval将工作,如果适当的名称在范围内,即array和dtype和float32。但您绝对应该考虑上述选项之一。
标签: python dictionary text