I have a netcdf4 file input.nc4 with variables alpha, beta, gamma. I want to create a new netcdf4 file output.nc4 with variable names alpha_new, beta_new, gamma_new. The attributes of alpha_new, beta_new and gamma_new should be those of alpha, beta and gamma respectively (in a loop) and the data is simply a numpy array. I am trying the following but do not know what am I doing wrong or whether it is the right method to do so or not?
import sys
import numpy as np
from netCDF4 import Dataset
input = Dataset('input.nc4', 'r')
output = Dataset('output.nc4', 'w', format='NETCDF4')
dict1 = {}
for name, variable in input.variables.items():
dict1[name] = variable
this = sys.modules[__name__]
for var_name,var_data in dict1.items():
file.createDimension(var_name,30)
var_output = output.createVariable('/Group_1/{}'.format(var_name), float, ('{}'.format(var_name),))
var_nc[:] = np.linspace(1,30,30)
setattr(this, '{}_new'.format(var_name) , var_nc[:])
for attr_name in var_data.ncattrs():
setattr(this,'vv{}.{}'.format(var_name,attr_name), getattr(var_data,attr_name))
output.close()
where attr_name are units, comments and least_significant_digit and are different for the three variables. But the above mentioned approach is not working and although the file is created with data, the attributes are not copied and are thus absent.