Reputation: 10267
Is it possible, with Python + netCDF4, to open an existing NetCDF file and change one of the dimensions from fixed size to an unlimited dimension, such that I can append data to it?
I found this question/answer, which lists several options for doing this with NCO/xarray, but I'm specifically looking for a method using the netCDF4 package.
Below is a minimal example which creates a NetCDF file with a fixed dimension (this part, of course, does not exist in reality, otherwise I could simply create the file with an unlimited dimension...), and then re-opens it in an attempt to modify the time
dimension. The netCDF4.Dimension time_dim
has a function/method isunlimited()
to test whether the dimension is unlimited or not, but nothing like e.g. make_unlimited()
, which I was hoping for.
import netCDF4 as nc4
import numpy as np
# Create dataset for testing
nc1 = nc4.Dataset('test.nc', 'w')
dim = nc1.createDimension('time', 10)
var = nc1.createVariable('time', 'f8', 'time')
var[:] = np.arange(10)
nc1.close()
# Read it back
nc2 = nc4.Dataset('test.nc', 'a')
time_dim = nc2.dimensions['time']
# ...
# (1) Make time_dim unlimited
# (2) Append some data
# ...
nc2.close()
Upvotes: 0
Views: 2200
Reputation: 592
Something like this...
# rename the old dimension
data.renameDimension('time_dim', 'tmp_dim')
# create a new unlimited dimension with the old fixed size dimension's name
data.createDimension('time_dim', None)
# copy the data from the renamed dimension
time_dim[:] = tmp_dim[:]
# delete the temporary dimension
del data.dimensions['tmp_dim']
Upvotes: 0