[Python] Modify NetCDF file to make dimension unlimited

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    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()

    Continue reading...

Compartilhe esta Página