Last active
June 30, 2022 04:59
-
-
Save guziy/8543562 to your computer and use it in GitHub Desktop.
A quick way to copy variables and metadata from one netcdf file to another using netcdf4-python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks That worked for me.
Cheers