import sys import netCDF4 as nc import numpy as np def main(fname, group, var_name): f = nc.Dataset(fname, mode='a') # this is the new variable that will be added to the existing netcdf file newvar = np.zeros((100, 50)) # create dimension 1 of the new variable in the netcdf file, if necessary dim1 = [k for k in f.dimensions.keys() if newvar.shape[0] == f.dimensions.keys()] if dim1 != []: dim1 = dim1[0] else: dim1 = 'newdim_1' f.createDimension(dim1, newvar.shape[0]) # create dimension 2 of the new variable in the netcdf file, if necessary dim2 = [k for k in f.dimensions.keys() if newvar.shape[1] == f.dimensions.keys()] if dim2 != []: dim2 = dim2[0] else: dim2 = 'newdim_2' f.createDimension(dim2, newvar.shape[1]) # create the new variable in the netcdf file nc_var = f.createVariable('{}/{}'.format(group, var_name), 'f8', (dim1, dim2)) # assign the value to the variable in the file nc_var[:] = newvar # assign local attribute to the new variable with name "attr_name" # and value "attr_value". attr_name has to be a string, attr_value can be anything setattr(f['{}/{}'.format(group, var_name)], 'attr_name', 'attr_value') f.close() if __name__ == '__main__': main(sys.argv[1], sys.argv[2], sys.argv[3])