Appending more datasets into an existing Hdf5 file without deleting other groups and datasets

M. Khubaib-ul-Hassan Khan picture M. Khubaib-ul-Hassan Khan · Jul 4, 2016 · Viewed 10.3k times · Source

I have an HDF5 file which contains groups and subgroups inside which there are datasets. I want to open the file and add some datasets to the groups. I took the following approach which is quite simple in python.

    import h5py
    f = h5py.File('filename.h5','w')
    f.create_dataset('/Group1/subgroup1/dataset4', data=pngfile)
    f.close()

The before file looked like this

Before File Image

After File looks like this

After File Image

but I want it to not delete other datasets and groups but rather just append the dataset4 in the line.

Answer

John Readey picture John Readey · Jul 4, 2016

Just like with the Python open() function, 'w' will truncate any existing file. Use the 'a' mode to add content to the file:

import h5py
f = h5py.File('filename.h5','a')
f.create_dataset('/Group1/subgroup1/dataset4', data=pngfile)
f.close()