如何使用HDF5存储和加载Python字典

问题描述 投票:1回答:1

我在加载HDF5文件的字典时遇到问题(我认为存储工作正常-正在创建文件并包含数据)。我收到以下错误:

ValueError:格式错误的节点或字符串:

我的代码是:

    def store_table(self, filename):
        table = dict()
        table['test'] = list(np.zeros(7,dtype=int))

        with h5py.File(filename, "w") as file:
            file.create_dataset('dataset_1', data=str(table))
            file.close()


    def load_table(self, filename):
        file = h5py.File(filename, "r")
        data = file.get('dataset_1')
        print(ast.literal_eval(data))

我已经使用ast方法在线阅读了[[literal_eval,但是它似乎无济于事...如何“解压” HDF5,使其再次成为字典?

任何想法都将不胜感激。
python dictionary hdf5
1个回答
0
投票
如果我了解您要做什么,这应该可以工作:

import numpy as np import h5py def store_table(filename): data = np.zeros(7,dtype=int) with h5py.File(filename, "w") as f: f.create_dataset('test', data=data, dtype=int) def load_table(filename): f = h5py.File(filename, 'r') data = f['test'][...] return data filename = "file.h5" store_table(filename) data = load_table(filename) print(data)

© www.soinside.com 2019 - 2024. All rights reserved.