read_dataset#
- mhm_tools.common.netcdf.read_dataset(file_path: str | Path | List[str | Path], use_mfdataset: bool = False, engine: str = 'netcdf4') Dataset[source]#
Load one or more NetCDF files into a single xarray.Dataset.
This function accepts either a single path (possibly containing shell-style wildcards), or a list of paths, and handles both:
Single-file case: opens it directly.
- Multi-file case:
If use_mfdataset=True, uses xarray.open_mfdataset for contiguous datasets.
Otherwise, opens each file individually and combines them via coordinates (attributes overridden).
- Parameters:
file_path (Union[str, Path, List[Union[str, Path]]]) – A file path (can include wildcards), or a list of explicit file paths.
use_mfdataset (bool, default False) – If True and multiple files are found, open them with xr.open_mfdataset. Otherwise, open each with xr.open_dataset and combine.
engine (str, default “netcdf4”) – The backend engine to use for opening NetCDF files.
- Returns:
An xarray Dataset containing the data from the specified file(s).
- Return type:
xr.Dataset
- Raises:
FileNotFoundError – If a wildcard pattern is provided but no files match.
Exception – Any exception raised by xarray when opening files is propagated after being logged.
Examples
Read a single file:
>>> ds = read_dataset("data/single_file.nc")
Read all files in a directory (recursively):
>>> ds = read_dataset("data/**/*.nc", use_mfdataset=True)
Read a fixed list of files:
>>> paths = ["data/part1.nc", "data/part2.nc"] >>> ds = read_dataset(paths)