本文介绍了使用python复制netcdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想使用Python复制netcdf文件.

I would like to make a copy of netcdf file using Python.

关于如何读取或写入netcdf文件的示例非常好,但是也许还有一个很好的方法来进行变量的输入,然后输出到另一个文件.

There are very nice examples of how to read or write netcdf-file, but perhaps there is also a good way how to make the input and then output of the variables to another file.

一个好用的方法会很不错,以便以最低的成本将尺寸和尺寸变量获取到输出文件中.

A good-simple method would be nice, in order to get the dimensions and dimension variables to the output file with the lowest cost.

推荐答案

我在 python netcdf上找到了此问题的答案:所有变量和属性都只有一个,但是我需要对其进行更改以使其与我的python/netCDF4版本(Python 2.7.6/1.0.4)一起使用.如果需要添加或减去元素,则可以进行适当的修改.

I found the answer to this question at python netcdf: making a copy of all variables and attributes but one, but I needed to change it to work with my version of python/netCDF4 (Python 2.7.6/1.0.4). If you needed to add or subtract elements, you would make the appropriate modifications.

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')

此代码段已经过测试.

这篇关于使用python复制netcdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:09