0

I am extracting data from netCDF files with Python code. I need to check if the netCDF files are in agreement with the CORDEX standards (CORDEX is a coordinated effort to carry modelling experiments with regional climate models). For this I need to access an attribute of the netCDF file. If the attribute is not found, then the code should go to the next file.

A snipet of my code is as follows:

import netCDF4

cdf_dataset = netCDF4.Dataset(file_2read)

try:
    cdf_domain = cdf_dataset.CORDEX_domain
    print(cdf_domain)

except:
    print('No CORDEX domain found. Will exit')
    ....some more code....

When the attribute "CORDEX_domain" is available everything is fine. If the attribute is not available then the following exception is raised.

AttributeError: NetCDF: Attribute not found

This is a third party exception, which I would say should be handled as a general one, but it is not, as I am not able to get my "print" inside the "except" statement to work or anything else for that matter. Can anyone point me the way to handle this? Thanks.

RIAF
  • 41
  • 6

1 Answers1

2

There is no need for a try/except block; netCDF4.Dataset has a method ncattrs which returns all global attributes, you can test if the required attribute is in there. For example:

if 'CORDEX_domain' in cdf_dataset.ncattrs():
    do_something()

You can do the same to test if (for example) a required variable is present:

if 'some_var_name' in cdf_dataset.variables:
    do_something_else()

p.s.: "catch alls" are usually a bad idea..., e.g. Python: about catching ANY exception

EDIT:

You can do the same for variable attributes, e.g.:

var = cdf_dataset.variables['some_var_name']
if 'some_attribute' in var.ncattrs():
    do_something_completely_else()
Bart
  • 9,825
  • 5
  • 47
  • 73
  • Thanks Bart, just what I was looking for. Works like a charm. Just have a couple of questions regarding this. 1) Do you know why does the exception is not caught? and 2) Is there such a method for "variable attributes"? – RIAF Apr 18 '18 at 10:29
  • I updated the answer. About why the exception isn't caught: no idea. I tried your code with another NetCDF file (which doesn't have a `CORDEX_domain` attribute, and it prints the `except` part without any problems/errors. – Bart Apr 18 '18 at 10:40
  • 1
    Thanks for the great response Bart. Will try the code somewhere else also, maybe I can find out what is the deal. – RIAF Apr 18 '18 at 12:28