-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata_extract.py
51 lines (39 loc) · 1.45 KB
/
metadata_extract.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- coding: latin-1 -*-
# Copyright CERFACS (http://cerfacs.fr/)
# Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
#
# Author: Christian Page (2017)
import json
from netCDF4 import Dataset, MFDataset
def netcdf_md_extract(in_file,
var_name,
md_list_file,
out_file
):
# Extract list of Metadata Attributes to extract
with open(md_list_file) as data_file:
md_list = json.load(data_file)
# Initialize output dict
md_out = { "metadata": { "global": {}, var_name: {} } }
# Open NetCDF input file to parse
srcfile = Dataset(in_file)
# Go through global attributes first, and extract
for key, value in md_list["metadata"]["global"].items():
if (value == True):
try:
md_out["metadata"]["global"][key] = getattr(srcfile, key)
except AttributeError:
md_out["metadata"]["global"][key] = ""
# Go through variable attributes. Extract.
for key, value in md_list["metadata"]["variable"].items():
if (value == True):
try:
md_out["metadata"][var_name][key] = getattr(srcfile.variables[var_name], key)
except AttributeError:
md_out["metadata"][var_name][key] = ""
# Close inpout file
srcfile.close()
# Dump output in json
with open(out_file, 'w') as fp:
json.dump(md_out, fp, indent=2)
fp.close()