Add a variable and a dimension to a given netCDF file in Python

Viewed 18

I would like to add a variable with dimensions to a given netCDF file. This is my code example which doesnt work so far.

import numpy as np 
import netCDF4 as nc

dataset = nc.Dataset("path", mode ="a") #the dataset in which the variable should be implemented
temp  = dataset.variables["3D_array"] #3D_array has the dimensions lat, lon, time; time with len==unlimited
lat = dataset.variables["latitude"][:]

tmean = (temp[:] * np.cos(np.pi/180. *lat[:, np.newaxis])).mean(axis=(1,2)) 

time = nc.num2date(
    dataset.variables['time'][:],
    units=dataset.variables['time'].units,
    calendar=dataset.variables['time'].calendar,
    only_use_cftime_datetimes=False,
    only_use_python_datetimes=True)

#now creating dimensions and variables

dataset.createDimension("tmean", len(time) #is now equal to 2029)
tmean = dataset.createVariable("tmean", f4 #dtype float32, dimension=("time"))

now i get the RuntimeError: NetCDF: String match to name in use.

Since I am new to netCDF i would love some help. Thank you!

0 Answers
Related