cfgrib - GRIB to NetCDF/CF via ecCodes

0.9.15.1 · active · verified Mon Apr 13

cfgrib is a Python interface developed by ECMWF that maps GRIB files to the NetCDF Common Data Model, adhering to the CF (Climate and Forecast) Conventions. It leverages the underlying C library ecCodes for efficient GRIB decoding and integrates seamlessly with xarray for data representation. The library is actively maintained by ECMWF, with regular releases addressing new features and bug fixes, typically every few months.

Warnings

Install

Imports

Quickstart

Demonstrates how to open a GRIB file using `cfgrib` with `xarray`'s `open_dataset` function and inspect its contents. Requires a GRIB file to be present.

import cfgrib
import xarray as xr
import os

# --- IMPORTANT: Obtain a GRIB file for this example ---
# cfgrib requires a GRIB file to operate. For a runnable example:
# 1. Download a sample GRIB file, e.g., from:
#    https://github.com/ecmwf/cfgrib/blob/main/tests/grib_files/era5-levels-members.grib
# 2. Save it as 'sample.grib2' in the same directory as this script,
#    or specify its full path.
#
# Alternatively, if you have `earthkit-data` installed:
# import earthkit.data
# ds = xr.open_dataset(earthkit.data.res_source('t.grib'), engine='cfgrib')

grib_file_path = "sample.grib2"

if not os.path.exists(grib_file_path):
    print(f"Warning: The GRIB file '{grib_file_path}' was not found.")
    print("Please download a sample GRIB file and place it in the current directory or update the path.")
    print("Skipping `open_dataset` call for this demonstration.")
else:
    try:
        # Open the GRIB file as an xarray Dataset
        # The `engine='cfgrib'` is crucial for xarray.open_dataset to use cfgrib
        ds = xr.open_dataset(grib_file_path, engine="cfgrib")

        print("\nDataset loaded successfully:")
        print(ds)

        # Access a data variable, e.g., 't' for temperature
        if 't' in ds:
            print("\nTemperature data (first 5 values):")
            print(ds['t'].isel(time=0, level=0).values.flatten()[:5])
        else:
            print("\nNo 't' variable found in the dataset. Available variables:", list(ds.data_vars))

    except Exception as e:
        print(f"An error occurred while opening the GRIB file: {e}")

view raw JSON →