Due to the lapse in federal government funding, NASA is not updating this website. We sincerely regret this inconvenience.
NASA Logo
Ocean Color Science Software

ocssw V2022
ncattredit.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 #
3 import sys
4 import os
5 import time
6 import datetime
7 import netCDF4 as nc
8 import numpy as np
9 
10 if len(sys.argv) != 3:
11  print('Usage:')
12  callseq = sys.argv[0] + ' file ' + 'attr-file'
13  print(callseq)
14  print('\nThis script modifies attributes in a netCDF file')
15  print('\tfile:\t\tsource file to modify')
16  print('\tattr-file:\tfile containig attribue=value pairs to modify\n')
17  print('\tTo delete an attribute, set the value to a blank string\n')
18  print('\tAttributes listed in the attr-file but not existing in the netCDF file\n\twill be added')
19  print('\tFor group attributes, prepend the attribute name with the group,\n\tdelineated with a "/", e.g.:')
20  print('\t\tnavigation_data/mycoolattribute=awesomeness')
21  sys.exit(1)
22 
23 inFile = sys.argv[1]
24 attrFile = sys.argv[2]
25 rootgrp = nc.Dataset(inFile, 'a')
26 
27 # generate string to update the history
28 processtime = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%S')
29 if 'history' in rootgrp.ncattrs():
30  history = nc.Dataset.getncattr(rootgrp,'history').rstrip() + '\n'+'['+processtime+'] '+os.path.basename(sys.argv[0])+ ' ' + sys.argv[1] + ' ' + sys.argv[2]
31 else:
32  history = '['+processtime+'] ' + os.path.basename(sys.argv[0]) + ' ' + sys.argv[1] + ' ' + sys.argv[2]
33 
34 attrs = open(attrFile,'r')
35 
36 for attr in attrs:
37  attrName,attrValue = attr.split('=')
38  attrValue = attrValue.rstrip()
39  group = rootgrp
40  try:
41  parts = attrName.split('/')
42  if len(parts) > 1:
43  attrName = parts.pop()
44  attrGroup = '/'.join(parts).strip()
45  group = rootgrp.createGroup(attrGroup)
46  except:
47  pass
48 
49  # Check to see if the attribute exists,
50  # if it does, delete it
51  try:
52  attrValueExisting = nc.Dataset.getncattr(group,attrName)
53  nc.Dataset.delncattr(group,attrName)
54  except:
55  pass
56 
57  # if starts with a quote it is a string
58  try:
59  if len(attrValue):
60  if attrValue.startswith('"'):
61  attrValue = attrValue.strip('"').encode('ascii')
62  nc.Dataset.setncattr(group,attrName,attrValue)
63  else:
64  # if has a comma it is an array
65  if "," in attrValue:
66  if attrValue.startswith('['):
67  attrValue = attrValue.lstrip('[').rstrip(']')
68  partsStr = attrValue.split(',')
69  if '.' in attrValue:
70  parts = np.array(partsStr).astype(np.dtype('f4'))
71  else:
72  parts = np.array(partsStr).astype(np.dtype('i4'))
73  nc.Dataset.setncattr(group,attrName,parts)
74 
75  else:
76  if '.' in attrValue:
77  nc.Dataset.setncattr(group,attrName,np.array(attrValue).astype(np.dtype('f4')))
78  else:
79  nc.Dataset.setncattr(group,attrName,np.array(attrValue).astype(np.dtype('i4')))
80  except Exception as e:
81  sys.exit("Whoops! Something went seriously wrong:\n"+ str(e))
82 
83 # update the history
84 nc.Dataset.setncattr(rootgrp,'history', history)
85 
86 
87 rootgrp.close()
void print(std::ostream &stream, const char *format)
Definition: PrintDebug.hpp:38
Definition: aerosol.c:136