使用python复制netcdf文件

msi*_*rva 4 python netcdf

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

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

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

小智 6

我在python netcdf上找到了此问题的答案:制作了所有变量和属性的一个副本,但一个副本,但是我需要对其进行更改以使其与我的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')
Run Code Online (Sandbox Code Playgroud)

此代码段已经过测试。


小智 5

如果您只想使用netCDF-4 API来复制任何 netCDF-4文件,即使是那些使用任意用户定义类型的变量的文件,这也是一个难题.netcdf4-python.googlecode.com上的netCDF4模块目前缺乏对具有可变长度成员或可变长度类型的复合基类型的复合类型的支持.

netCDF-4 C发行版提供的nccopy实用程序显示可以仅使用C netCDF-4 API复制任意netCDF-4文件,但这是因为C API完全支持netCDF-4数据模型.如果您将目标限制为仅复制仅使用googlecode模块支持的平面类型的netCDF-4文件,则nccopy.c中使用的算法应该可以正常工作,并且应该非常适合Python中更优雅的实现.

一个不那么雄心勃勃的项目会更容易复制任何netCDF"经典格式"文件的Python程序,因为netCDF-3支持的经典模型没有用户定义的类型或递归类型.该程序甚至适用于同样使用压缩和分块等性能功能的netCDF-4经典模型文件.