Last active
December 12, 2015 03:59
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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