小编典典

python netcdf:复制所有变量和属性,但复制一个

python

我需要在netcdf文件中处理一个实际上包含许多属性和变量的变量。我认为无法更新netcdf文件

我的方法如下:

  1. 从原始文件获取要处理的变量
  2. 处理变量
  3. 将所有数据从原始netcdf复制,但将已处理的变量复制到最终文件
  4. 将已处理的变量复制到最终文件

我的问题是对步骤3进行编码。我从以下内容开始:

def  processing(infile, variable, outfile):
        data = fileH.variables[variable][:]

        # do processing on data...

        # and now save the result
        fileH = NetCDFFile(infile, mode="r")
        outfile = NetCDFFile(outfile, mode='w')
        # build a list of variables without the processed variable
        listOfVariables = list( itertools.ifilter( lamdba x:x!=variable , fileH.variables.keys() ) )
        for ivar in listOfVariables:
             # here I need to write each variable and each attribute

如何在不重建整个数据结构的情况下将所有数据和属性保存在完整的代码中?


阅读 523

收藏
2020-12-20

共1个答案

小编典典

这就是我刚刚使用和工作的内容。@arne的答案已针对Python 3更新,还包括复制变量属性:

import netCDF4 as nc
toexclude = ['ExcludeVar1', 'ExcludeVar2']

with netCDF4.Dataset("in.nc") as src, netCDF4.Dataset("out.nc", "w") as dst:
    # copy global attributes all at once via dictionary
    dst.setncatts(src.__dict__)
    # copy dimensions
    for name, dimension in src.dimensions.items():
        dst.createDimension(
            name, (len(dimension) if not dimension.isunlimited() else None))
    # copy all file data except for the excluded
    for name, variable in src.variables.items():
        if name not in toexclude:
            x = dst.createVariable(name, variable.datatype, variable.dimensions)
            dst[name][:] = src[name][:]
            # copy variable attributes all at once via dictionary
            dst[name].setncatts(src[name].__dict__)
2020-12-20