Skip to content

Instantly share code, notes, and snippets.

@m1t9
Last active March 30, 2017 13:03
Show Gist options
  • Save m1t9/e24c73a287f88fe4a25b4a65c438a774 to your computer and use it in GitHub Desktop.
Save m1t9/e24c73a287f88fe4a25b4a65c438a774 to your computer and use it in GitHub Desktop.
This script reads netCDF files. NetCDF (Network Common Data Form) is a set of software libraries and self-describing, machine-independent data formats that support the creation, access, and sharing of array-oriented scientific data.

READ NETCDF FILES

This script reads netCDF files. NetCDF (Network Common Data Form) is a set of software libraries and self-describing, machine-independent data formats that support the creation, access, and sharing of array-oriented scientific data.

from netCDF4 import Dataset
import numpy as np
import sys

print('\nStart...\n')

# sys.stdout.write('-'+key+' ')
nc_fileID = str(input('.nc file name (without format): ')) + '.nc'
try:
    file_chk = open(nc_fileID)
except FileNotFoundError:
    sys.exit('\nError! File not found')

root = Dataset(nc_fileID)
dims = root.dimensions
ndims = len(dims)

dic = {}
dic2 = {}
print('\nAvailable variables in selected .NC file:\n')
vars = root.variables
nvars = len(vars)
n = 0
for var in vars:
    # sys.stdout.write('-'+var+' ')
    print('#',n,'   ',var, vars[var].shape)
    dic[str(var)] = n
    l = vars[var].shape
    dic2[str(var)] = len(l)
    n += 1
print('\n')

nc_data = []
print('Write the variables you want to read (through the gap):\n')
iter_var = []
iter_var.append(input().split(' '))
iter_var = iter_var[0]
try:
    for v in iter_var:
        dic[v]
except KeyError:
    sys.exit('\nVariable name error\n')

for i in iter_var:
    if (dic2[i] == 1):
        nc_data.append(np.array(root.variables[i][:], dtype=np.float32))
    if (dic2[i] == 2):
        nc_data.append(np.array(root.variables[i][:,:], dtype=np.float32))
    if (dic2[i] == 3):
        nc_data.append(np.array(root.variables[i][:,:,:], dtype=np.float32))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment