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.

0

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

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"?
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.
Thanks for the great response Bart. Will try the code somewhere else also, maybe I can find out what is the deal.

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.