Stand With Ukraine

Tuesday, January 21, 2014

netcdf4-python copying variables from one netcdf file to another

This has arisen as a problem of converting NETCDF4 to NETCDF3_CLASSIC which is still used by some old software. I did try nc4tonc3 provided with netCDF4 but that one also wanted the input file in NETCDF4_CLASSIC format... That is why I wrote this little script to actually copy variables and dimensions. There were no attributes in the files, so I did not care to handle attributes.

# -*- coding: utf-8 -*-
from netCDF4 import Dataset
#input file
dsin = Dataset("crop.nc")
#output file
dsout = Dataset("crop.nc3", "w", format="NETCDF3_CLASSIC")
#Copy dimensions
for dname, the_dim in dsin.dimensions.iteritems():
print dname, len(the_dim)
dsout.createDimension(dname, len(the_dim) if not the_dim.isunlimited() else None)
# Copy variables
for v_name, varin in dsin.variables.iteritems():
outVar = dsout.createVariable(v_name, varin.datatype, varin.dimensions)
print varin.datatype
# Copy variable attributes
outVar.setncatts({k: varin.getncattr(k) for k in varin.ncattrs()})
outVar[:] = varin[:]
# close the output file
dsout.close()
view raw Converter.py hosted with ❤ by GitHub
From a comment by Nikolay Koldunov, there is a utility for this tasks nccopy ...