In this python example, we will introduce how to read a hdf5 file using python. In order to read a hdf5 file, we should answer these two questions:
- How to open a hdf5 file?
- How to read data in hdf5 file?
We will answer these question one by one.
Step 1: open a hdf5 file
In python, we can use h5py package and use h5py.File() to open a hdf5 file. Here is an example:
import h5py f2 = h5py.File('data.hdf5', 'r')
Step 2: read data in hdf5 file
In python, we can use hdf5 file keys() function to list all datasets in it. Here is an example:
>>> list(f2.keys()) ['dataset_01', 'dataset_02']
Then we can read each dataset by its key name. For example:
>>> dset1 = f2['dataset_01'] >>> data = dset1[:] >>> data array([[ 1, 99, 79, 46], [69, 4, 29, 60], [56, 94, 16, 16], [52, 13, 37, 86]], dtype=int32) >>> list(dset1.attrs.keys()) ['scale', 'offset'] >>> dset1.attrs['scale'] 0.01