我想使用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')
这段代码已经过测试。
import xarray as xr
input = xr.open_dataset('ncfile.nc')
input.to_netcdf('copy_of_ncfile.nc')
import nctoolkit as nc
data = nc.open_data("infile.nc")
data.to_nc("outfile.nc")
请参考如何在Python中复制文件?:netcdf文件与其他文件没有区别,因此它应该符合您的需求。