8

我有一个大小为(3997,29)的numpy数组(arr)。我正在使用这个数组来创建一个数据集。该数组具有整数和浮点变量。所以 dtype 是参考。但是当我执行它时,我得到以下错误。

“ValueError:不是位置 ID(无效的对象 ID)”

with h5py.File("test1.h5", 'w') as f:
     grp = f.create_group('Nodes')

with h5py.File("test1.h5", 'r+') as f:
     grp = f.require_group('Nodes')

ref_dtype = h5py.special_dtype(ref=h5py.Reference)

arrshape = np.shape(arr)

dset = grp.create_dataset('Init' ,arrshape, dtype = ref_dtype , data= arr)

错误发生在最后一行。以下是回溯消息
dset = f.create_dataset('Init' ,arrshape, dtype = ref_dtype , data= arr)

文件“C:\Users\rupesh.n\AppData\Local\Continuum\anaconda3\lib\site-packages\h5py_hl\group.py”,第 108 行,在 create_dataset dsid = dataset.make_new_dset(self, shape, dtype, data , **kwds)

文件“C:\Users\rupesh.n\AppData\Local\Continuum\anaconda3\lib\site-packages\h5py_hl\dataset.py”,第 137 行,在 make_new_dset dset_id = h5d.create(parent.id, None, tid , sid, dcpl=dcpl)

文件“h5py_objects.pyx”,第 54 行,在 h5py._objects.with_phil.wrapper

文件“h5py_objects.pyx”,第 55 行,在 h5py._objects.with_phil.wrapper 中

文件“h5py\h5d.pyx”,第 79 行,在 h5py.h5d.create

ValueError: Not a location id (Invalid object id)

4

2 回答 2

16

当有人尝试使用封闭句柄创建新数据集时,经常会发生此错误。如果您正在迭代,请确保您没有在循环内关闭文件。我和OP有同样的问题。

于 2018-08-30T18:27:31.273 回答
1

这个问题有点老了,但如果其他人在这里遇到同样的问题,我会稍微澄清一下答案。@WilderField 是正确的,但要更清楚一点。

在最后一行:

dset = grp.create_dataset('Init' ,arrshape, dtype = ref_dtype , data= arr)

grp指向 h5py.Group在以下位置使用的已关闭:

with h5py.File("test1.h5", 'r+') as f:
     grp = f.require_group('Nodes')

因为grp被设置为指向上下文管理器内部的组只是该with...上下文管理器grp中的一个开放组。当上下文管理器退出时,HDF 和与 HDF 关联的所有组/数据集都将关闭。此行为是为了防止 HDF 被丢失的指向 HDF 对象的指针保持打开状态。

解决方案是创建h5py.Dataset上下文管理器的内部,即:

with h5py.File("test1.h5", 'r+') as f:
     grp = f.require_group('Nodes')
     dset = grp.create_dataset('Init' ,arrshape, dtype = ref_dtype , data= arr)

同样,一旦上下文管理器关闭,dset它将指向一个Closed h5py.Dataset所以除非你真的想用它做更多的事情,否则调用它就足够了,grp.create_dataset(...)而不会将 return 分配给dset.

于 2020-12-01T19:33:00.560 回答