Search code examples
pythonh5py

h5py stores only 0s in datasets


I'm trying to store some values in an h5py file, but every time I try to store a matrix in a dataset, all the matrix elements are replaced by 0s. Here's an example

I create the file like this:

output_file=h5py.File('output_file', 'w')

dset=output_file.create_dataset('dset', (3,3))

for k in range(3):
    for l in range(3):
        dset[k][l]=1.

I then read the file and try to print the output

file=h5py.File('output_file', 'r')

print(file['dset'][:])

the output is

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

all the 1s have been turned into 0s. What am I doing wrong?


Solution

  • This is explicitly covered in the manual. When you do dset[k], you create a temporary array. It is this array's l'th element that you set when you do dset[k][l] = 1.0. That temporary array is not the h5py dataset that you want to be referring to – you aren't touching the latter at all.

    In short: index with dset[k, l] instead.