Skip to content

Instantly share code, notes, and snippets.

@jhamman
Last active December 12, 2015 03:59
Show Gist options
  • Save jhamman/4711205 to your computer and use it in GitHub Desktop.
Save jhamman/4711205 to your computer and use it in GitHub Desktop.
A simple way to read in all (or some) variables from a netcdf file.
#!/usr/local/bin/python
import numpy as np
from netCDF4 import Dataset
##################################################################################
## Read netCDF Inputs
## Read data from input netCDF.
##################################################################################
def read_netcdf(ncFile,vars = [],coords = False, verbose = False):
"""
Read data from input netCDF. Will read all variables if none provided.
Will also return all variable attributes.
Both variables (data and attributes) are returned as dictionaries named by variable
"""
#if verbose: print 'Reading input data vars:', vars, ', from file:',ncFile
f = Dataset(ncFile,'r')
if vars==[]: vars = f.variables.keys()
d={}
a={}
if coords:
if isinstance(vars,str):
d[vars] = f.variables[vars][coords]
a[vars] = f.variables[vars].__dict__
else:
for var in vars:
d[var] = f.variables[var][coords]
a[var] = f.variables[var].__dict__
else:
if isinstance(vars,str):
d[vars] = f.variables[vars][:]
a[vars] = f.variables[vars].__dict__
else:
for var in vars:
d[var] = f.variables[var][:]
a[var] = f.variables[var].__dict__
f.close()
return d,a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment