简短回答:不。
我不是底层 HDF5 库的专家,但我认为他们没有这种能力(而 h5py 只是一个包装器)。 (某种)好消息:如果您尝试写入超出分配的大小,h5py 将引发异常。
下面的代码扩展了您的示例以进行演示。
with h5py.File('SO_68389770.h5','w') as h5f:
dset = h5f.create_dataset("my_dataset", (1024,), maxshape=(None,))
size = 100
for i in range(10):
arr = np.random.random(size)
start, end = i*size, i*size+size
dset[start:end] = arr
这适用于range(10)。对于range(11),您将收到此错误:
TypeError: Can't broadcast (100,) -> (24,)
下面的代码通过在写入前检查dset.shape[0] 干净地处理任何大小。
with h5py.File('SO_68389770.h5','w') as h5f:
dset = h5f.create_dataset("my_dataset", (1024,), maxshape=(None,))
size = 100
for i in range(13):
arr = np.random.random(size)
start, end = i*size, i*size+size
if dset.shape[0] >= end :
dset[start:end] = arr
else:
print(f'insufficient dset size, end={end}; resizing')
dset.resize(end,axis=0)
dset[start:end] = arr