python将OpenDap加载到NetcdfFile [英] python load OpenDap to NetcdfFile
问题描述
我正在使用URL从opendap服务器打开netcdf数据(数据的子集).当我打开它时(据我所知),直到请求该变量之前,才实际加载数据.我想将数据保存到磁盘上的文件中,该怎么办?
I am opening netcdf data from an opendap server (a subset of the data) using an URL. When I open it the data is (as far as I can see) not actually loaded until the variable is requested. I would like to save the data to a file on disk, how would I do this?
我目前有:
import numpy as np
import netCDF4 as NC
url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
set = NC.Dataset(url) # I think data is not yet loaded here, only the "layout"
varData = set.variables['varname'][:,:] # I think data is loaded here
# now i want to save this data to a file (for example test.nc), set.close() obviously wont work
希望有人可以提供帮助,谢谢!
Hope someone can help, thanks!
推荐答案
这很简单;创建一个新的NetCDF文件,然后复制所需的任何内容:)幸运的是,在从输入文件复制正确的尺寸,NetCDF属性,...方面,这可以在很大程度上实现自动化.我快速编写了这个示例,输入文件也是本地文件,但是如果使用OPenDAP进行读取已经可以了,那么它应该以类似的方式工作.
It's quite simple; create a new NetCDF file, and copy whatever you want :) Luckily this can be automated for a large part, in copying the correct dimensions, NetCDF attributes, ... from the input file. I quickly coded this example, the input file is also a local file, but if the reading with OPenDAP already works, it should work in a similar way.
import netCDF4 as nc4
# Open input file in read (r), and output file in write (w) mode:
nc_in = nc4.Dataset('drycblles.default.0000000.nc', 'r')
nc_out = nc4.Dataset('local_copy.nc', 'w')
# For simplicity; copy all dimensions (with correct size) to output file
for dim in nc_in.dimensions:
nc_out.createDimension(dim, nc_in.dimensions[dim].size)
# List of variables to copy (they have to be in nc_in...):
# If you want all vaiables, this could be replaced with nc_in.variables
vars_out = ['z', 'zh', 't', 'th', 'thgrad']
for var in vars_out:
# Create variable in new file:
var_in = nc_in.variables[var]
var_out = nc_out.createVariable(var, datatype=var_in.dtype, dimensions=var_in.dimensions)
# Copy NetCDF attributes:
for attr in var_in.ncattrs():
var_out.setncattr(attr, var_in.getncattr(attr))
# Copy data:
var_out[:] = var_in[:]
nc_out.close()
希望,如果没有让我知道的话,它会有所帮助.
Hope it helps, if not let me know.
这篇关于python将OpenDap加载到NetcdfFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!