使用python复制netcdf文件

我想用
Python制作netcdf文件的副本.

有很好的例子来说明如何读取或写入netcdf文件,但也许有一个很好的方法如何输入然后输出变量到另一个文件.

一个好的简单方法会很好,以便以最低的成本将维度和维度变量输出到输出文件.

最佳答案 我在
python netcdf: making a copy of all variables and attributes but one找到了这个问题的答案,但我需要改变它以使用我的python / netCDF4版本(Python 2.7.6 / 1.0.4).如果需要添加或减去元素,则需要进行适当的修改.

import netCDF4 as nc

def create_file_from_source(src_file, trg_file):
    src = nc.Dataset(src_file)
    trg = nc.Dataset(trg_file, mode='w')

    # Create the dimensions of the file
    for name, dim in src.dimensions.items():
        trg.createDimension(name, len(dim) if not dim.isunlimited() else None)

    # Copy the global attributes
    trg.setncatts({a:src.getncattr(a) for a in src.ncattrs()})

    # Create the variables in the file
    for name, var in src.variables.items():
        trg.createVariable(name, var.dtype, var.dimensions)

        # Copy the variable attributes
        trg.variables[name].setncatts({a:var.getncattr(a) for a in var.ncattrs()})

        # Copy the variables values (as 'f4' eventually)
        trg.variables[name][:] = src.variables[name][:]

    # Save the file
    trg.close()

create_file_from_source('in.nc', 'out.nc')

此片段已经过测试.

点赞