我想用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')
此片段已经过测试。
如果您只想使用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经典模型文件。
请参阅How do I copy a file in python?:netcdf文件与任何其他文件没有区别,因此它应该符合您的需求
只是为了澄清我想要的东西。
我不得不修改一些变量,但我也想保留原始文件。那么,现在我也会做这个任务:
然而,格里菲斯,拉斯和其他人都承认他们对这个问题的回答。