Overview
- Attributes in HDF5 allow datasets to be self-descriptive.
- Any metadata that describe the datasets and groups can be attached to groups and datasets of HDF5 through attributes.
- In h5py, both the Group and Dataset objects have the python attribute attrs through which attributes can be stored.
- The attrs is an instance of AttributeManager. AttributeManager provides dictionary like access for reading and writing attributes.
Example
# Example Python program that adds attributes to a HDF5 group and a HDF5 dataset
import h5py
import numpy.random
# Create a HDF5 file
fileOpenMode = "w";
hdfFileName = "WithAttributes.HDF5";
hdf5File = h5py.File(hdfFileName, fileOpenMode);
# Create a group at root level
aGroup = hdf5File.create_group("/A");
datasetShape = (24,);
aDataset = aGroup.create_dataset("/A/D", datasetShape);
# Add
aDataset.attrs["SensorName"] = "FluidVelocity-X1Y5";
aDataset.attrs["SensorType"] = "Differential";
aDataset.attrs["SensorLocation"] = "40.71, -74.00";
# Assign hourly readings
for i in range(0, 24):
aDataset[i] = numpy.random.uniform(80, 100, 1)[0];
# Print dataset along with attributes
print("(Attribute, Value:)");
for item in aDataset.attrs.items():
print(item);
for i in range(0, aDataset.shape[0]):
print(aDataset[i]);Output
(Attribute, Value:)
('SensorLocation', '40.71, -74.00')
('SensorName', 'FluidVelocity-X1Y5')
('SensorType', 'Differential')
86.06291
89.932724
97.62169
91.05482
85.80139
90.10574
95.83731
86.68407
94.6496
92.08971
81.00686
86.006996
97.08245
84.83142
82.231895
99.718704
90.461914
86.364334
81.27478
93.38981
91.627525
89.78677
84.98252
85.19031