SoFunction
Updated on 2025-03-02

Summary of various ways to read nc files in Python

Preface

In Python, there are many ways to read NetCDF (.nc) document. Common methods include using the following libraries:

1. netCDF4

This is one of the most commonly used libraries that provide the ability to directly read, write and process NetCDF files. It supports NetCDF file formats for version 3 and version 4.

Install

pip install netCDF4

usage

import netCDF4 as nc

# Open the filedataset = ('')

# View the dimensions of the fileprint(())

# View file variablesprint(())

# Read variable datatemp_data = ['temperature'][:]
()

2. xarray

xarrayIt is a very powerful library suitable for processing multidimensional data. It's withnetCDF4The library is compatible and provides advanced operational capabilities.

Install

pip install xarray

usage

import xarray as xr

# Read NetCDF filesds = xr.open_dataset('')

# View variables in the datasetprint(ds)

# Access data of a variabletemp_data = ds['temperature'].values

# Close the dataset()

3. h5py

NetCDF 4's file format is based on HDF5, so you can also useh5pyto process NetCDF 4 files, although this method is more underlying.

Install

pip install h5py

usage

import h5py

# Open NetCDF4 filefile = ('', 'r')

# View file contentprint(list(()))

# Read datadata = file['/temperature'][:]
()

4. SciPy

SciPy also provides basic support for NetCDF files, although its functionality is relatively limited and is mainly used to process older NetCDF 3 files.

Install

pip install scipy

usage

from  import netcdf

# Open the filefile = netcdf.netcdf_file('', 'r')

# Read variable datatemp_data = ['temperature'].data
()

5. Pseudonetcdf

If you need to deal with non-standard NetCDF file formats, you can usePseudonetcdf

Install

pip install Pseudonetcdf

usage

import PseudoNetCDF as pnc

# Open the filencfile = ('', format='ioapi')

# Read variablestemp_data = ['temperature'][:]

Different methods have their own advantages and disadvantages. If advanced processing of multidimensional data is required,xarrayIt is a good choice; if it is just a simple read or write,netCDF4Library is the most direct choice.

Summarize

This is the end of this article about various ways to read nc files in Python. For more related Python reading nc files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!