python 创建netcdf_如何使用python netCDF4创建netCDF文件?

I am learning how to use netCDF4 using Pyhton module in Anaconda. I am trying to append values to two variables I have created time and field:

from netCDF4 import Dataset

import numpy as np

root_grp = Dataset('py_netcdf4.nc', 'w', format='NETCDF4')

root_grp.description = 'Example simulation data'

ndim = 128 # Size of the matrix ndim*ndim

xdimension = 0.75

ydimension = 0.75

# dimensions

root_grp.createDimension('time', None)

root_grp.createDimension('x', ndim)

root_grp.createDimension('y', ndim)

# variables

time = root_grp.createVariable('time', 'f8', ('time',))

x = root_grp.createVariable('x', 'f4', ('x',))

y = root_grp.createVariable('y', 'f4', ('y',))

field = root_grp.createVariable('field', 'f8', ('time', 'x', 'y',))

# data

x_range = np.linspace(0, xdimension, ndim)

y_range = np.linspace(0, ydimension, ndim)

x[:] = x_range

y[:] = y_range

for i in range(5):

time[i] = i*50.0

field[i,:,:] = np.random.uniform(size=(len(x_range), len(y_range)))

root_grp.close

But now when I print one of the variables I get that it's empty(!!):

Python 2.7.10 |Anaconda 2.4.1 (64-bit)| (default, Sep 15 2015, 14:50:01)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

Anaconda is brought to you by Continuum Analytics.

Please check out: http://continuum.io/thanks and https://anaconda.org

>>> from netCDF4 import Dataset

>>> root_grp = Dataset('py_netcdf4.nc', 'r', format='NETCDF4')

>>> print root_grp.variables["field"][:,:,:]

[]

>>>

What am I doing wrong here?

解决方案

This works:

from netCDF4 import Dataset

import numpy as np

root_grp = Dataset('py_netcdf4.nc', 'w', format='NETCDF4')

root_grp.description = 'Example simulation data'

ndim = 128 # Size of the matrix ndim*ndim

xdimension = 0.75

ydimension = 0.75

# dimensions

root_grp.createDimension('time', None)

root_grp.createDimension('x', ndim)

root_grp.createDimension('y', ndim)

# variables

time = root_grp.createVariable('time', 'f8', ('time',))

x = root_grp.createVariable('x', 'f4', ('x',))

y = root_grp.createVariable('y', 'f4', ('y',))

field = root_grp.createVariable('field', 'f8', ('time', 'x', 'y',))

# data

x_range = np.linspace(0, xdimension, ndim)

y_range = np.linspace(0, ydimension, ndim)

x[:] = x_range

y[:] = y_range

for i in range(5):

time[i] = i*50.0

field[i,:,:] = np.random.uniform(size=(len(x_range), len(y_range)))

root_grp.close()

The only difference is that I call the close() method: root_grp.close().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值