1

I am loading multiple NetCDF files in python 3 (on Windows) using MFDataset, and am wanting to loop through the variables and look at the attributes. I am able to load and read the data fine, however I am wanting to access the attributes associated with the variables.

import netCDF4
file = r"C:\netcdf_files\data*.nc" #wildcarded NetCDF files

with netCDF4.MFDataset(file) as src:       
    for name, variable in src.variables.items():            
        for attrname in variable.ncattrs():
           print("{} -- {}".format(attrname, variable.getncattr(attrname)))

When the above snippet runs I am given a the following exception:

Traceback (most recent call last):
File "netCDF4\_netCDF4.pyx", line 5026, in netCDF4._netCDF4._Variable.__getattr__ (netCDF4\_netCDF4.c:57060)
KeyError: 'getncattr'

For a single file NetCDF file, loaded with Dataset:

import netCDF4
file = r"C:\netcdf_files\data1.nc" #single, explicit file

with netCDF4.Dataset(file) as src:       
    for name, variable in src.variables.items():            
        for attrname in variable.ncattrs():
           print("{} -- {}".format(attrname, variable.getncattr(attrname)))

The above runs just fine, printing out the variable attributes as desired.

I am still very new to working with NetCDF files - is there a way to access the variable attributes when loading data using MFDataset? Thanks!

2
  • Please provide the code which causes the error, preferably a minimal working (or in this case, not working) example. Commented Dec 17, 2015 at 10:06
  • Hi Bart, I have updated the post with some working examples - I hope they help to explain my issue. Cheers. Commented Dec 17, 2015 at 10:58

1 Answer 1

3

It seems that the getncattr function is indeed not available when using MFDataset. This solution seems to work with both Dataset and MFDataset:

import netCDF4

src = netCDF4.Dataset("drycblles.1.nc")

for name, variable in src.variables.items():            
    for attrname in variable.ncattrs():
        print("{} -- {}".format(attrname, getattr(variable, attrname)))
        # or :
        #print("{} -- {}".format(attrname, variable.getncattr(attrname))) 


src = netCDF4.MFDataset("drycblles.*.nc")

for name, variable in src.variables.items():            
    for attrname in variable.ncattrs():
        print("{} -- {}".format(attrname, getattr(variable, attrname)))

In both cases I get the same output.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.