首页 > 解决方案 > 如何在python中将数据附加到h5文件?

问题描述

当数据进入时,我想向 HDF5 文件添加越来越多的数据。我尝试了以下操作:首先使用第一个数组创建一个数据集,然后尝试通过调整其大小向 h5 文件添加一个值。

import os
import h5py
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 9, 8, 87, 2, 3, 5, 12, 14, 16]).astype(int)
y = 9
path = "out.h5"
with h5py.File(path, "a") as f:
    dset = f.create_dataset("somedata", data=x, maxshape=(None,))
    dset[:] = y
    print(dset.shape)

    for i in range(3):
        dset.resize(dset.shape[0] + 1, axis=0)
        dset["somedata"] = y

some = h5py.File("out.h5", "r")
for x in some["somedata"]:
    print(x)

但它给我一个错误:

File "/anaconda3/lib/python3.7/site-packages/h5py/_hl/dataset.py", line 582, in __setitem__
    raise TypeError("Illegal slicing argument (not a compound dataset)")
TypeError: Illegal slicing argument (not a compound dataset)

标签: pythonhdf5h5py

解决方案


您似乎正在尝试调整数据集的大小并使用y. 你能试试这个吗?

import h5py
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 9, 8, 87, 2, 3, 5, 12, 14, 16]).astype(int)
y = 9
path = "out.h5"
with h5py.File(path, "a") as f:
    dset = f.create_dataset('somedata', data=x, maxshape=(None,))
    dset[:] = y
    print(dset.shape)

    for i in range(3):
        dset.resize(dset.shape[0] + 1, axis=0)
        dset[:] = y

with h5py.File("out.h5", "r") as some:
    for x in some["somedata"]:
        print(x)

推荐阅读