Python:从.txt读取字典,字符串键和数组类型值

时间:2018-02-06 18:10:06

标签: python dictionary text

我已将字典保存为txt文件

strstr

保存的txt文件包含

f = open("dict_imageData.txt","a")
f.write( str(dict_imageData) + "\n" )
f.close()

我在加载此字典并拆分键和值时遇到问题。我试过拆分和eval但是没有用,因为最后有一个dtype语句。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

感谢您的评论,是的我知道使用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)