加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用python复制netcdf文件

发布时间:2020-12-20 11:24:17 所属栏目:Python 来源:网络整理
导读:我想用 Python制作netcdf文件的副本. 有很好的例子来说明如何读取或写入netcdf文件,但也许有一个很好的方法如何输入然后输出变量到另一个文件. 一个好的简单方法会很好,以便以最低的成本将维度和维度变量输出到输出文件. 解决方法 我在 python netcdf: makin
我想用 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')

此片段已经过测试.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读