How do I programmatically list all variables of a NetCDF file that I have read in using netCDF4 and Python?
import netCDF4
dset = netCDF4.Dataset('test.nc')
How do I programmatically list all variables of a NetCDF file that I have read in using netCDF4 and Python?
import netCDF4
dset = netCDF4.Dataset('test.nc')
dset.variables.keys()
would provide you with a list of the variables.
To list all variable names as strings just do:
list(dset.variables.keys())
or simple
list(dset.variables)
For a NetCDF file that contains a group structure, it's necessary to access each group. In those cases, to generate and show a list of all the variables, the following has worked for me:
import netCDF4
def expand_var_list(var_list, group):
for var_key, _ in group.variables.items():
var_list.append(var_key)
for _, sub_group in group.groups.items():
expand_var_list(var_list, sub_group)
all_vars = []
with netCDF4.Dataset("test.nc", "r") as root_group:
expand_var_list(all_vars, root_group)
print(all_vars)
This code adds each group's variables to the overall variable list, before checking to see if there are sub-groups. If there are sub-groups, it does the same with each of those, recursively.
As the first commenter pointed out, the initial answer does not show which group each variable was contained within. Here is updated code, that puts the variable names into a dictionary so you can see which variable belongs to which group:
def expand_var_dict(var_dict, group):
for var_key, _ in group.variables.items():
if group.name not in var_dict.keys():
var_dict[group.name] = list()
var_dict[group.name].append(var_key)
for _, sub_group in group.groups.items():
expand_var_dict(var_dict, sub_group)
all_vars = dict()
with netCDF4.Dataset("test.nc", "r") as root_group:
expand_var_dict(all_vars, root_group)
print(all_vars)
The result should be something like this:
{'/': ['root_level_var1', 'root_level_var2'],
'group1': ['x', 'y', 'z'],
'group2': ['k', 'm']
}