10 if len(sys.argv) != 3:
12 callseq = sys.argv[0] +
' file ' +
'attr-file'
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')
24 attrFile = sys.argv[2]
25 rootgrp = nc.Dataset(inFile,
'a')
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]
32 history =
'['+processtime+
'] ' + os.path.basename(sys.argv[0]) +
' ' + sys.argv[1] +
' ' + sys.argv[2]
34 attrs = open(attrFile,
'r')
37 attrName,attrValue = attr.split(
'=')
38 attrValue = attrValue.rstrip()
41 parts = attrName.split(
'/')
43 attrName = parts.pop()
44 attrGroup =
'/'.join(parts).strip()
45 group = rootgrp.createGroup(attrGroup)
52 attrValueExisting = nc.Dataset.getncattr(group,attrName)
53 nc.Dataset.delncattr(group,attrName)
60 if attrValue.startswith(
'"'):
61 attrValue = attrValue.strip(
'"').encode(
'ascii')
62 nc.Dataset.setncattr(group,attrName,attrValue)
66 if attrValue.startswith(
'['):
67 attrValue = attrValue.lstrip(
'[').rstrip(
']')
68 partsStr = attrValue.split(
',')
70 parts = np.array(partsStr).astype(np.dtype(
'f4'))
72 parts = np.array(partsStr).astype(np.dtype(
'i4'))
73 nc.Dataset.setncattr(group,attrName,parts)
77 nc.Dataset.setncattr(group,attrName,np.array(attrValue).astype(np.dtype(
'f4')))
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))
84 nc.Dataset.setncattr(rootgrp,
'history', history)