I have two netCDF files: file1.nc
and file2.nc
The only difference is that file1.nc
contains one variable 'rho' which I want to append to file2.nc
but by modifying the variables. The original file2.nc
does not contain 'rho' in it.
I am using Python module netCDF4.
import netCDF4 as ncd
file1data=ncd.Dataset('file1.nc')
file1data.variables['rho']
<class 'netCDF4._netCDF4.Variable'> float64 rho(ocean_time, s_rho, eta_rho, xi_rho)
long_name: density anomaly
units: kilogram meter-3
time: ocean_time
grid: grid
location: face
coordinates: lon_rho lat_rho s_rho ocean_time
field: density, scalar, series
_FillValue: 1e+37
unlimited dimensions: ocean_time
current shape = (2, 15, 1100, 1000)
filling on
So rho has shape of [2,15,1100,1000] but while adding to file2.nc, I only want to add rho[1,15,1100,1000] i.e. only the data of the second time step. This will result in 'rho' in file2.nc being of shape [15,1100,1000]. But I have been unable to do so.
I have been trying code like this:
file1data=ncd.Dataset('file1.nc')
rho2=file1data.variables['rho']
file2data=ncd.Dataset('file2.nc','r+') # I also tried with 'w' option; it does not work
file2data.createVariable('rho','float64')
file2data.variables['rho']=rho2 # to copy rho2's attributes
file2data.variables['rho'][:]=rho2[-1,15,1100,1000] # to modify rho's shape in file2.nc
file2data.close()
What am I missing here?