red_tiger red_tiger - 11 months ago 49
Python Question

python create netCDF with attributes

I have a XML file which I want to serve as the base for a netCDF file. I am ok with reading the XML file and creating the netCDF file, both in python.

Each group or variable in the XML file has attributes and I want to add them to the netCDF file. My problem is that I do not know the names of the attributes and this whole thing needs to be automatic.

The usual way of creating and adding an attribute in python for netCDF would be like this:

grp.attr = 'name'

I now need to do this automatic, I do not know what 'attr' really is. If I use 'attr' as a variable name, 'attr' will be added to the netCDF file and not the actual name.

I will try and illustrate this. Lets say I have three attributes for my group called:

<attribute name="alphabet" value="abc"/>
<attribute name="number" value="42"/>
<attribute name="version" value="ncc1701"/>

I want these attributes to be in the file, but at time of writing I have no insight where which attribute will be, what its name is etc. So I loop over all attributes and would write a code similar to this:

for att in list_attributes:
attr_name =
attr_value = att.value
grp.attr_name = attr_value

If I do this I will end up with one attribute in my netCDF file with the name 'attr_name' and the value 'ncc1701' instead of the intended three attributes.

Any ideas how to solve this? Thanks.

Answer Source

Use setncattr method from netCDF4 package in the loop.