-1

nc.variables[i].units is showing an error attribute not found. i am trying to extract data from netcdf file. how to extract data of a particular longitude or latitude?

from netCDF4 import Dataset

nc=Dataset("test.nc",'r')

for i in nc.variables:

    print(i,nc.variables[i].units,nc.variables[i].shape) 

lat=nc.variables['lat'][:]
print(lat)

the output is as follows:

area meter2 (128, 256)
lat degrees_north (128,)
Traceback (most recent call last):
File "C:\Users\harsh\Desktop\cv\test_netcdf.py", line 7, in <module>
print(i,nc.variables[i].units,nc.variables[i].shape) #nc.variable[i].units
File "netCDF4\_netCDF4.pyx", line 4303, in 
netCDF4._netCDF4.Variable.__getattr__
File "netCDF4\_netCDF4.pyx", line 4114, in 
netCDF4._netCDF4.Variable.getncattr
File "netCDF4\_netCDF4.pyx", line 1392, in netCDF4._netCDF4._get_att
File "netCDF4\_netCDF4.pyx", line 1857, in 
netCDF4._netCDF4._ensure_nc_success
AttributeError: NetCDF: Attribute not found
James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

1

Take a closer look at this section

for i in nc.variables:

    print(i,nc.variables[i].units,nc.variables[i].shape) 

In this for loop i is not an integer. Since this is evaluated as a for each loop it represents the current variable, not the index at which that variable exists. You have a few options here

Option one: use range instead

for i in range(len(nc.variables)):

    print(i,nc.variables[i].units,nc.variables[i].shape) 

Option two: use a zip to have a reference to the variable and an integer
As pointed out by Bart, Enumerate is a nicer way of doing this. See his comment below for that

for i, variable in zip(range(len(nc.variables)), nc.variables):

    print(i, variable.units, variable.shape) 

Option three: avoid using i altogether

for variable in nc.variables:

    print(variable.units, variable.shape) 
alexanderhurst
  • 456
  • 3
  • 8
  • 1
    Another alternative: `for i, variable in enumerate(nc.variables):`, which is a bit shorter than the `zip` version, but basically does the same.. – Bart Jun 13 '19 at 18:24
  • 1
    @Bart oh right, I always forget about enumerate(x). Added a reference to you to my answer, Cheers. – alexanderhurst Jun 13 '19 at 19:00