Install & Compatibility
Where this runs
tested against v1.7.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
build_error
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 4.3s · import 0.354s · 123MB
123MB installed
● package 123MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Dataset
✓ from netCDF4 import Dataset
The primary class for opening, creating, and interacting with NetCDF files.
This quickstart demonstrates how to create a NetCDF4 file, define dimensions (including an unlimited dimension for time), create variables with attributes, write NumPy array data into these variables, and then read the data back. It uses `Dataset` for file operations and `numpy` for data generation.
import os
from netCDF4 import Dataset
import numpy as np
# Define a dummy NetCDF file path
filename = 'example.nc'
# Create a new NetCDF file in write mode ('w')
with Dataset(filename, 'w', format='NETCDF4') as nc_file:
# Create dimensions
nc_file.createDimension('x', 10)
nc_file.createDimension('y', 5)
nc_file.createDimension('time', None) # 'None' for unlimited dimension
# Create variables
x_var = nc_file.createVariable('x', 'i4', ('x',))
y_var = nc_file.createVariable('y', 'i4', ('y',))
time_var = nc_file.createVariable('time', 'f8', ('time',))
data_var = nc_file.createVariable('temperature', 'f4', ('time', 'y', 'x'))
# Add attributes to variables
data_var.units = 'Celsius'
data_var.long_name = 'Air Temperature'
# Write data to variables
x_var[:] = np.arange(10)
y_var[:] = np.arange(5)
# Write data for the first time step
time_var[0] = 0.0
data_var[0, :, :] = np.random.rand(5, 10) * 30 + 273.15 # Kelvin example
# Write data for a second time step (demonstrates unlimited dimension)
time_var[1] = 1.0
data_var[1, :, :] = np.random.rand(5, 10) * 30 + 273.15
print(f"Successfully created and wrote to {filename}")
# Read data from the NetCDF file in read mode ('r')
with Dataset(filename, 'r') as nc_file:
print(f"\nOpened {filename} for reading:")
print(f"File format: {nc_file.data_model}")
print(f"Dimensions: {list(nc_file.dimensions.keys())}")
print(f"Variables: {list(nc_file.variables.keys())}")
temp_data = nc_file.variables['temperature'][:, :, :]
print(f"Shape of 'temperature' data: {temp_data.shape}")
print(f"Units of 'temperature': {nc_file.variables['temperature'].units}")
print(f"Sample temperature data:\n{temp_data[0, 0, 0]:.2f} {nc_file.variables['temperature'].units}")
# Clean up the created file
os.remove(filename)
print(f"\nCleaned up {filename}")
Debug
Known issues
breakingStarting with version 1.7.4 and when using free-threaded Python (e.g., Python 3.13+ with `PYTHON_FREETHREADING=1`), `netcdf4-python` may experience segfaults if `netCDF4` functions are called from multiple threads concurrently. The underlying `netcdf-c` library is not thread-safe, and while `netcdf4-python` has internal locking, care must be taken.fixUsers must ensure that all calls to `netCDF4` library functions are made from a single thread, or implement external threading locks if concurrent access is absolutely necessary.
affects: >=1.7.4 (especially with free-threaded Python)
gotchaInstallation via `pip` usually provides pre-compiled binary wheels that bundle the necessary `netCDF C` and `HDF5 C` libraries. However, if building from source, or on less common systems, these external C libraries must be installed separately and configured correctly (e.g., via `nc-config` or environment variables) for `netcdf4-python` to compile and function.fixFor ease of installation, use `conda` (`conda install netcdf4`) or ensure your system has the `netCDF C` and `HDF5 C` libraries installed and discoverable by the Python build process (e.g., by setting `NETCDF4_DIR` or `LD_LIBRARY_PATH`).
affects: All versions (especially when not using pre-built wheels)
breakingPrior to version 1.4.0, `netcdf4-python` would only return masked arrays if a slice of data explicitly contained missing values. From version 1.4.0 onwards, the default behavior changed to always return masked arrays for primitive and enum data types if `missing_value` or `_FillValue` attributes are defined, regardless of whether the slice contains actual missing data.fixTo revert to the pre-1.4.0 behavior (return unmasked NumPy arrays unless missing values are present), use `Dataset.set_auto_mask(False)` or `Variable.set_auto_mask(False)` after opening the dataset. Alternatively, adapt your code to expect masked arrays by default.
affects: >=1.4.0
deprecatedMany examples and older codebases use `datetime.datetime.utcnow()` when assigning time attributes (e.g., to `nc.history`). Python's `datetime.utcnow()` is deprecated and will raise `DeprecationWarning` in modern Python versions, scheduled for removal in future versions.fixReplace `datetime.datetime.utcnow()` with `datetime.datetime.now(datetime.timezone.utc)` for timezone-aware UTC datetimes, or `datetime.datetime.now(datetime.UTC)` in Python 3.11+. Remember to import `datetime` and `timezone` from the `datetime` module.
affects: All versions, when used with Python versions where `utcnow()` is deprecated (Python 3.11+)
breakingVersions 1.7.0 and 1.7.1 introduced a regression that prevented opening remote OPeNDAP files, resulting in `curl` errors. This issue was likely resolved in subsequent patch releases.fixIf encountering issues with remote OPeNDAP file access on these specific versions, upgrade to a newer patch release (e.g., 1.7.2 or later) or downgrade to a stable prior version (e.g., 1.6.5).
affects: 1.7.0, 1.7.1
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'netCDF4'
The `netCDF4` package is either not installed in the current Python environment or the Python interpreter being used does not have access to the installed package. This is a common installation or environment configuration issue.
fixInstall the `netCDF4` library using pip or conda in your active Python environment. If using a virtual environment or conda environment, ensure it is activated before installation.
```bash
pip install netcdf4
# or, if using conda
conda install netcdf4
```
OSError: [Errno -101] NetCDF: HDF error
This error often indicates problems related to file permissions (attempting to write to a read-only file), file corruption, or conflicts when trying to open a file for both reading and writing (e.g., with 'r+' mode). It can also occur if the underlying HDF5 library encounters an issue.
fixCheck the file permissions and ensure you have write access if opening in 'r+' or 'w' mode. If only reading, use 'r' mode. Verify the file's integrity; if corrupted, try to regenerate or obtain a valid copy. Sometimes, explicitly setting `HDF5_USE_FILE_LOCKING=FALSE` as an environment variable can mitigate issues related to file locking.
```python
# If only reading
import netCDF4
rootgrp = netCDF4.Dataset('myfile.nc', 'r')
# To change file permissions (Linux/macOS)
# import os
# os.chmod('myfile.nc', 0o755) # Make it readable and writable
``` RuntimeError: NetCDF: Not a valid ID
This error typically means the file you are trying to open or operate on is either not a valid NetCDF file, is corrupted, or has already been closed. It can also occur if attempting operations on a NetCDF file object after the associated file has been implicitly or explicitly closed.
fixVerify the file is a legitimate and uncorrupted NetCDF file using external tools (e.g., `ncdump` from the NetCDF utilities). Ensure that you are opening the file correctly and that the `netCDF4.Dataset` object remains in scope and is not prematurely closed before operations are complete, especially when iterating or using `xarray` without proper context management. Using a `with` statement for `netCDF4.Dataset` objects can help ensure proper file handling.
```python
import netCDF4
try:
with netCDF4.Dataset('valid_file.nc', 'r') as nc_file:
# Perform operations within this block
print(nc_file.variables.keys())
except RuntimeError as e:
print(f"Error opening file: {e}. Check file integrity.")
``` AttributeError: NetCDF: Write to read only
This error occurs when you attempt to modify a NetCDF file (e.g., add a variable, write data, or change an attribute) that was opened in read-only mode ('r').
fixOpen the NetCDF file in write mode ('w'), append mode ('a'), or read-write mode ('r+') if you intend to make modifications. Note that 'w' will overwrite an existing file.
```python
import netCDF4
# To write to a new file or overwrite an existing one
# rootgrp = netCDF4.Dataset('new_or_overwrite.nc', 'w', format='NETCDF4')
# To append to an existing file
rootgrp = netCDF4.Dataset('existing_file.nc', 'a')
# To open for reading and writing
# rootgrp = netCDF4.Dataset('existing_file.nc', 'r+')
# Example of writing after opening in a writable mode
rootgrp.createDimension('x', 10)
var = rootgrp.createVariable('my_var', 'f4', ('x',))
var[:] = range(10)
rootgrp.close()
``` ValueError: numpy.dtype size changed, may indicate binary incompatibility. Expected X from C header, got Y from PyObject
This error indicates a binary incompatibility between the `netcdf4` library and your installed `numpy` version. It typically happens when `numpy` is updated, but `netcdf4` (which has C extensions linked against a specific `numpy` API version) is not rebuilt or reinstalled against the new `numpy` version.
fixReinstall or update the `netcdf4` package to ensure it is built against the current `numpy` version. It's often best to do this in a clean environment or specify exact versions to avoid conflicts.
```bash
pip uninstall netcdf4 numpy cftime
pip install numpy netcdf4 cftime
# or if using conda
conda update numpy
conda install netcdf4 cftime
```
If the issue persists, try creating a fresh conda environment and installing `numpy`, `cftime`, and `netcdf4` there.
Upgrade
Version history
1.7.4latest on PyPI · released Jan 5, 2026
Audit
Dependencies
numpyrequiredEssential for numerical array manipulation and data storage within NetCDF variables.
cftimerequiredProvides datetime objects that handle calendar systems and dates outside the standard Gregorian range, often used in climate data.
certifirequiredRequired for locating SSL certificates, enabling access to OPeNDAP HTTPS URLs since version 1.6.4.
netCDF C libraryrequiredThe core underlying C library that `netcdf4-python` interfaces with. Binary wheels often bundle this, but source installs or specific environments may require manual installation and configuration (e.g., via `nc-config`).
HDF5 C libraryrequiredNetCDF-4 format is built on HDF5. Similar to the NetCDF C library, this may require manual installation for source builds.
mpi4pyoptionalOptional. Required for parallel I/O capabilities when working in an MPI environment.
CythonoptionalOptional. Required if building `netcdf4` from source.