【问题标题】:Appending to h5py groups附加到 h5py 组
【发布时间】:2018-05-12 22:27:07
【问题描述】:

我有以下结构的文件:

  • 时间1
  • 索引 1
  • 值 x
  • 值 y
  • 时间1
  • 索引 2
  • 值 x
  • 值 y
  • 时间 2
  • 索引 1
  • ...

我希望使用 h5py 将文件转换为 hdf5 格式,并将每个索引中的值排序到单独的组中。

我的方法是

f = h5py.File(filename1,'a')
trajfile = open(filename2, 'rb')

    for i in range(length_of_filw):
        time = struct.unpack('>d', filename2.read(8))[0]
        index = struct.unpack('>i', filename2.read(4))[0]       
        x = struct.unpack('>d', filename2.read(8))[0]
        y = struct.unpack('>d', filename2.read(8))[0]

        f.create_dataset('/'+str(index), data=[time,x,y,z])

但是通过这种方式,我无法附加到组(我只能向每个组写入一次......)。错误信息是“RuntimeError: Unable to create link (name already exists)”。

有没有办法追加到组中?

【问题讨论】:

    标签: python python-2.7 hdf5 h5py


    【解决方案1】:

    可以根据需要多次写入数据集 - 您不能拥有两次同名数据集。这是你得到的错误。请注意,您正在创建一个数据集,同时您将一些数据放入其中。为了向它写入其他数据,它必须足够大以容纳它。

    无论如何,我相信您混淆了组和数据集。 组是使用例如创建的

    grp = f.create_group('bar') # this create the group '/bar'
    

    并且您想将数据集存储在数据集中,如您所说的那样创建:

    dst = f.create_dataset('foo',shape=(100,)) # this create the dataset 'foo', with enough space for 100 elements.
    

    您只需要创建一次组和数据集 - 但您可以通过它们的句柄(grp 和 dst)引用它们,以便写入它们。

    我建议您先浏览一次文件,使用“shape”参数创建所需的组和数据集以适当调整大小,然后使用实际数据填充数据集。

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 1970-01-01
      • 2014-01-22
      • 2013-12-23
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多