import numpy as np from Scientific.IO.NetCDF import NetCDFFile def createFile(FileName,lats,lons): # create a file object File = NetCDFFile(FileName,'w') # Create dimensions and associated variables # lat File.createDimension('lat',len(lats)) var = File.createVariable('lat','d',('lat',)) var.long_name = 'latitude' var.units = 'degrees north' var[:] = lats # lon File.createDimension('lon',len(lons)) var = File.createVariable('lon','d',('lon',)) var.long_name = 'longitude' var.units = 'degrees east' var[:] = lons # time # (this is a "record dimension", meaning it doesn't have predefined) File.createDimension('time',None) var = File.createVariable('time','d',('time',)) var.long_name = 'time' var.units = '' # create a data variable called jim # note that the 'd' here means the field is type float var = File.createVariable('jim','d',('time','lat','lon')) var.long_name = 'James' var.units = 'J' # return the file object return File # define some lats and lons and create a file lats = np.arange(181)*1. - 90. lons = np.arange(360)*1. File = createFile('jim.nc',lats,lons) # write some data into the file nlat = len(lats) nlon = len(lons) x = np.zeros((nlat,nlon))*0. # creates a field of shape (nlat,nlon) pre-filled with zeros # multiply by 0. to make sure it has type float # (otherwise it will be integer) # write as the first time instant File.variables['jim'][0,:,:] = x[:,:] File.variables['time'][0] = 1 # write as the 2nd time instant File.variables['jim'][1,:,:] = x[:,:]+1. File.variables['time'][1] = 2 # CLOSE THE FILE -- VERY IMPORTANT !!!! File.close()