Python:从.txt、字符串键和数组类型值读取字典
我已将字典保存为txt文件Python:从.txt、字符串键和数组类型值读取字典,python,dictionary,text,Python,Dictionary,Text,我已将字典保存为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=floa
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)}
我无法加载此词典并拆分键和值。我尝试了拆分和求值,但没有成功,因为最后有一个dtype语句
有什么建议吗?谢谢你的评论,是的,我知道使用JSON和pickle,但我更感兴趣的是使用.txt文件。我解决了我的问题,找到了如下解决方案: 首先,我将MyEncoder类定义为:
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(MyEncoder, self).default(obj)
由于我的键是字符串,而我的值是数组,所以在编写键值对之前,我将值转储为
dict_imageData[key]=json.dumps(np.float32(np.array(values)),cls=MyEncoder)
现在,我将字典写入文件,如下所示
with open('dict_imageData.txt', 'a') as file:
file.write(json.dumps(dict_imageData))
file.write("\n")
为了从.txt文件中读回字典,我使用eval
with open('dict_imageData.txt','r') as inf:
lineno = 0
for line in inf:
lineno = lineno + 1
print("line number in the file: ", lineno)
dicts_from_file = dict()
dicts_from_file = (eval(line))
for key,value in dicts_from_file.items():
print("key: ", key, "value: ", value)
是的,我建议您不要简单地将字典的字符串表示形式转储到文本文件中,并自行制作自己的序列化格式,而是依赖现有的众多标准之一,即JSON、YAML(基于文本的)和pickle(二进制的)。由于您使用的是numpy
,最好的可能是numpy
特定格式的numpy。保存或多个命名数组…另请参见:注意:eval
如果适当的名称在范围内,即array
和dtype
和float32
。但你绝对应该考虑上面提到的选项之一。