Page 1 of 1

How to create netCDF file using python ?

PostPosted: Tue Mar 29, 2016 2:13 pm
by yiboj
You need netCDF python library in order to read and write netCDF files. If your system does not have this library installed, you can download them from uniData at [url]https://github.com/Unidata/netcdf4-python[/url].

Here is the sample code for reading and writing netCDF file, and you can also download the script here at: [url]ftp://podaac.jpl.nasa.gov/allData/common/sw/nc_writers/netcdf_write.py[/url] and the sample data file at [url]ftp://podaac.jpl.nasa.gov/allData/common/sw/nc_writers/data/20160101-NCDC-L4LRblend-GLOB-v01-fv02_0-AVHRR_OI.nc[/url]

Feel free to modify the code to fit your need.

[code]#~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
from netCDF4 import Dataset
import numpy as np
import os

### Read in sample netCDF file ##################################################################

infilename='data/20160101-NCDC-L4LRblend-GLOB-v01-fv02_0-AVHRR_OI.nc'
ncin = Dataset(infilename, 'r')
lons = ncin.variables['lon'][:]
lats = ncin.variables['lat'][:]
sst = ncin.variables['analysed_sst'][:]
ncin.close()

nlat = lats.size
nlon = lons.size

### Write into netCDF file ######################################################################

# Create the new netCDF file
outfilename = 'test.nc'
fid = Dataset(outfilename,'w', format='NETCDF3_64BIT')
# Define the dimensions
lat = fid.createDimension('lat', nlat) # Unlimited
lon = fid.createDimension('lon', nlon) # Unlimited

# Create global attributes
fid.title = "This is a test file"
fid.institution = "PODAAC of JPL"
fid.summary = "One day of SST data"
fid.acknowledgment = "The data from PODAAC"
fid.date_created = "20151026"

# Create each data variable
nc_var = fid.createVariable('lats', 'f8',('lat'))
fid.variables['lats'][:] = lats
fid.variables['lats'].standard_name='latitude'
fid.variables['lats'].units='degrees_north'
fid.variables['lats'].comment='Latitude'

nc_var = fid.createVariable('lons', 'f8',('lon'))
fid.variables['lons'][:] = lons
fid.variables['lons'].standard_name='longitude'
fid.variables['lons'].units='degrees_east'
fid.variables['lats'].comment='Longitude'

nc_var = fid.createVariable('sst', 'f8',('lon', 'lat'))
fid.variables['sst'][:] = sst
fid.variables['sst'].units='Kelvin'
fid.variables['sst'].comment='analysed_sst'

fid.close()[/code]

Re: How to create netCDF file using python ?

PostPosted: Mon Aug 08, 2016 10:47 pm
by jenifferhomes
NETCDF reader supports various flavors of NETCDF and the basic reader which is used when output from a specific code cannot be identified supports some of the most common conventions.

This code takes advantage of rectilinear grid support in basic NETCDF reader in order to write rectilinear meshes with non-uniform cell sizes.

Code: Select all
from numpy import shape
from Scientific.IO.NetCDF import NetCDFFile
import numpy as np
 
# Write a variable with rectilinear coordinates to NETCDF.
def write_rectilinear(file, var, varname, x_coord, y_coord):
    nx = len(x_coord)
    ny = len(y_coord)
 
    # Reshape for 2D
    my_data = np.reshape(var,(ny,nx),'F')
 
    # Create dimensions:
    file.createDimension('nx', nx)
    file.createDimension('ny', ny)
 
    x = file.createVariable('nx', 'd', ('nx',))
    y = file.createVariable('ny', 'd', ('ny',))
 
    # transfer the coordinate variables:
    x[:] = x_coord
    y[:] = y_coord
 
    # Create data variable in NetCDF.
    data = file.createVariable(varname, 'd', ('ny','nx'))
 
    # transfer the data variables:
    data[:] = my_data
 
 
# coordinate information:
x_coord = [0,2,4,6,8,10,12]
y_coord = [0, 5, 10]
 
# number of points:
nx = len(x_coord)
ny = len(y_coord)
 
# Create a nodal data variable
nodal = []
for i in range(nx):
    for j in range(ny):
        nodal = nodal + [j*nx + i]
 
# Write the file.
file = NetCDFFile('rectilinear.nc', 'w')
write_rectilinear(file, nodal, 'data', x_coord, y_coord)
file.close()

Re: How to create netCDF file using python ?

PostPosted: Sun Aug 14, 2016 11:59 am
by yiboj
thanks for sharing your code with the community

Re: How to create netCDF file using python ?

PostPosted: Mon Dec 05, 2016 5:29 pm
by rabernat
xarray is a great way to output a netcdf file using python:
http://xarray.pydata.org/en/stable/io.html#netcdf

It uses netCDF internally, but the syntax is much more user friendly.

Re: How to create netCDF file using python ?

PostPosted: Tue Dec 06, 2016 9:38 am
by yiboj
thanks for sharing the info, xarray is definitely a great tool to manipulate netcdf file