使用python复制netcdf文件

发布于 2021-01-29 14:10:53

我想使用Python制作netcdf文件的副本。

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

一个好的方法很不错,以便以最低的成本获得尺寸和尺寸变量到输出文件。

关注者
0
被浏览
95
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    我在python
    netcdf上
    找到了此问题的答案:制作了所有变量和属性的一个副本,但一个副本,但我需要对其进行更改以使其与我的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')
    

    此代码段已经过测试。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看