read_nc.py
from netCDF4 import Dataset
import numpy as np
file = 'file.nc'
nc_obj=Dataset(file)
print(nc_obj)
print('---------------------------------------')
for var_name in nc_obj.variables.keys():
print(f'var name: {var_name}')
var = nc_obj.variables[var_name]
for arrt_name in var.ncattrs():
print(f'arrt name: {arrt_name}, arrt value: {var.__dict__[arrt_name]}')
print('')
print('---------------------------------------')
for var_name in nc_obj.variables.keys():
var = nc_obj.variables[var_name]
data = var[:]
data = np.array(data)
if '_FillValue' in var.__dict__:
fillvalue = var.__dict__['_FillValue']
data = np.where(data==fillvalue, data, np.nan)
if 'missing_value' in var.__dict__:
missing_value = var.__dict__['missing_value']
data = np.where(data==missing_value, data, np.nan)
if 'valid_min' in var.__dict__:
valid_min = var.__dict__['valid_min']
data = np.where(data<valid_min, data, np.nan)
if 'valid_max' in var.__dict__:
valid_max = var.__dict__['valid_max']
data = np.where(data>valid_max, data, np.nan)
if 'valid_range' in var.__dict__:
valid_range = var.__dict__['valid_range']
data = np.where(data<valid_range[0], data, np.nan)
data = np.where(data>valid_range[1], data, np.nan)
scale_factor = var.__dict__.get('scale_factor', 1.0)
add_offset = var.__dict__.get('add_offset', 0.0)
data = data * scale_factor + add_offset
print(data)
print('')
print('---------------------------------------')
|