2016-01-21 59 views
0

我正在學習如何在Anaconda中使用Pyhton模塊使用netCDF4。我想追加值的兩個變量,我創建timefield如何用python netCDF4創建一個netCDF文件?

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 

但現在當我打印的變量,我得到的一個,它是空的(!!):

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"][:,:,:] 
[] 
>>> 

什麼我在這裏做錯了嗎?

回答

2

這工作:

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() 

唯一的區別是,我稱之爲close()方法:root_grp.close()

+0

爲了避免這樣的錯誤(例如'close'方法中缺少括號),請使用[帶聲明的python](https://www.python.org/dev/peps/pep-0343/),如[這個例子](http://stackoverflow.com/q/31819754)。 – j08lue