0

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.

MNK
  • 634
  • 4
  • 18

1 Answers1

1

To my knowledge, setattr only sets existing netCDF4 attributes, any attributes it creates are attached to the python instance (not inside the dataset / file). Instead, you need to create a new attribute; without a method for directly creating attributes, you can use a workaround of creating an arbitrarily named attribute by directly setting it and then renaming it.

def set_or_create_attr(var, attr_name, attr_value):
    if attr_name in var.ncattrs(): 
        var.setncattr(attr_name, attr_value)
        return
    var.UnusedNameAttribute = attr_value
    var.renameAttribute("UnusedNameAttribute", attr_name)
    return

Using that function in place of setattr should do the trick, the var argument being the dataset or variable the attribute should be attached to.

J Lossner
  • 129
  • 10