'how to write data to a h5py dataset
I'm going crazy here - for some reason, I can't find out how to change a dataset in h5py. I first create a file:
i = h.File('C:\\Users\Bob\Desktop\blob.h5','w')
I then create a dataset within the file:
i.create_dataset("data",(100,100,100))
Finally, I try to write to the dataset:
i['data'][0][0][0] = 5
However, when I print, I don't get 5 back!
print(i['data'][0][0][0])#returns 0
I tried closing and reopening the file, but that didn't help. Any suggestions would be greatly appreciated!
Solution 1:[1]
So far, I haven't been able to find a way to mutate the contents of a dataset, but here's how to successfully create a new dataset. First, store the data in a list (this could be a multi-dimensional numpy array instead):
l = [1,2,3]
Then, create the dataset:
i.create_dataset("array", data=l)
arr = i["array"]
print(arr[1])
will now correctly display the value 2
Solution 2:[2]
Change the file mode argument for h5py.File from w
to r+
for read/write or a
for read/write/create. See https://docs.h5py.org/en/stable/high/file.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | JMS |
Solution 2 | Nevermore |