Recipe: Python program to read data from downloaded file

Problem

We want to read a downloaded data file using Python.

Solution

For the purpose of this example, we assume that we have already downloaded the file c1440_NR.inst01hr_3d_T_Cv.20060918_0900z.nc4 from the ftp server. For more information about file naming conventions, and how to download a file from the ftp server, please follow the links in the #See Also section.

Code (using netcdf4-python)

Here we use the netcdf4-python package to read the data file. If the command

> python -c "import netCDF4"

does not return any error, we have the package installed.

The code below reads the global temperature data from file, computes the maximum and minimum temperatures and plots (using the matplotlib package) the surface temperature

#!/usr/bin/env python

import sys
import numpy as np
import netCDF4 as nc4
import matplotlib.pyplot as plt

from mpl_toolkits.basemap import Basemap

rootgrp = nc4.Dataset('c1440_NR.inst01hr_3d_T_Cv.20060918_0900z.nc4', 'r')

# read air temperature
print 'Reading T for time=37...',; sys.stdout.flush()
T = rootgrp.variables['T'][:,:,:]
print 'done.'; sys.stdout.flush()
print T[0,5,:,:].shape

# min/max
print 'min(T):', np.min(T)
print 'max(T):', np.max(T)

# set up cylindrical map
m = Basemap(
    projection='cyl',
    llcrnrlat=-90, urcrnrlat=90,
    llcrnrlon=-180, urcrnrlon=180,
    resolution='c'
    )

m.drawcoastlines(linewidth=0.5)
m.drawmapboundary()

# plot contour
level = 71
X = np.arange(-180.0, 180.0, .5)
Y = np.arange(-90.0, 90.1, .5) # 90 is the last element
cp = plt.contour(X, Y, T[0,level,:,:], 20, zorder=2)
plt.clabel(cp, inline=1, fontsize=9)
plt.title('Air temperature at the surface')
plt.show()

Discussions

See Also

  1. Recipe: File naming conventions
  2. Recipe: Retrieve (global) data from FTP server

No Warranty

Copyright