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))