我需要在netcdf文件中处理一个实际上包含许多属性和变量的变量。我认为无法更新netcdf文件
我的方法如下:
我的问题是对步骤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
如何在不重建整个数据结构的情况下将所有数据和属性保存在完整的代码中?
这就是我刚刚使用和工作的内容。@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__)