h5netcdf: NetCDF4 via h5py

1.8.1 · active · verified Thu Apr 09

h5netcdf is an open-source Python package that provides an interface for the netCDF4 file-format, reading and writing local or remote HDF5 files directly via h5py or h5pyd. It aims to offer netCDF4 capabilities without relying on the Unidata netCDF C library. The current version is 1.8.1, and it maintains a regular release cadence, with recent patch and minor releases occurring every few months.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a NetCDF4 file, define dimensions, create a variable, write data, add an attribute, create a group, and then read the data back using the `h5netcdf.File` (new API) interface.

import h5netcdf
import numpy as np
import os

file_path = 'my_test_data.nc'

# Write data using the new API
with h5netcdf.File(file_path, 'w') as f:
    f.dimensions = {'x': 5, 'y': 3}
    var = f.create_variable('temperature', ('x', 'y'), 'f4')
    var[:] = np.random.rand(5, 3)
    var.units = 'Kelvin'
    f.create_group('forecast_data')

print(f"Successfully wrote data to {file_path}")

# Read data
with h5netcdf.File(file_path, 'r') as f:
    print(f"Dimensions: {list(f.dimensions.keys())}")
    temp = f.variables['temperature']
    print(f"Variable 'temperature' shape: {temp.shape}")
    print(f"Variable 'temperature' units: {temp.units}")
    print(f"First few values: {temp[:2, :2]}")
    if 'forecast_data' in f.groups:
        print("Group 'forecast_data' exists.")

# Clean up
os.remove(file_path)

view raw JSON →