我使用URL从opendap服务器(数据的子集)打开netcdf数据。当我打开它时,数据(据我所见)直到变量被请求时才被实际加载。我想要将数据保存到磁盘上的文件中,我该如何操作?
我目前有:
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希望有人能帮上忙,谢谢!
发布于 2017-07-06 22:57:28
它非常简单;创建一个新的NetCDF文件,然后复制您想要的任何东西:)幸运的是,在复制正确的尺寸、NetCDF属性时,这可以在很大程度上自动完成。从输入文件中。我快速地编写了这个示例,输入文件也是一个本地文件,但是如果使用OPenDAP的读取已经正常工作,它应该会以类似的方式工作。
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()希望它能帮上忙,如果不能,请告诉我。
发布于 2017-07-07 01:07:59
如果你可以使用xarray,它应该是这样工作的:
import xarray as xr
url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
ds = xr.open_dataset(url, engine='netcdf4') # or engine='pydap'
ds.to_netcdf('test.nc')xarray documentation提供了另一个示例来说明如何做到这一点。
https://stackoverflow.com/questions/44947031
复制相似问题