-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy_netcdf_file_without_variables.py
executable file
·63 lines (50 loc) · 1.97 KB
/
copy_netcdf_file_without_variables.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
"""
Make a copy of a netCDF file retaining dimensions
and attributes but exclude the variables.
Phillip J. Wolfram
01/14/2016
"""
import netCDF4
import sys, socket, os, datetime
def copy_netcdf_file_without_variables(infile, outfile):
"""
Copy dimensions and attributes from infile netCDF file to outfile.
Phillip J. Wolfram
01/14/2016
"""
ifile = netCDF4.Dataset(infile,'r')
ofile = netCDF4.Dataset(outfile,'w',format='NETCDF4_CLASSIC')
# transfer dimensions
for dim in ifile.dimensions.values():
ofile.createDimension(dim.name, len(dim))
# transfer global attributes
for name, value in zip(ifile.__dict__.keys(), ifile.__dict__.values()):
ofile.setncattr(name, value)
# copy time values
ofile.createVariable('xtime','c', ('Time','StrLen'))
ofile.variables['xtime'][:] = ifile.variables['xtime'][:]
# modify history and store metadata
callcmd = ' '.join(sys.argv)
ofile.history = callcmd + '; ' + ofile.history
ofile.meta_cwd = os.getcwd()
ofile.meta_host = socket.gethostname()
ofile.meta_call = ' '.join(sys.argv)
ofile.meta_user = os.getenv('USER')
ofile.meta_time = str(datetime.datetime.now())
ifile.close()
ofile.close()
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--infile", dest="inputfilename", \
help="Input file to be copied sans variables, of form '*.nc'", metavar="FILE")
parser.add_option("-o", "--outfile", dest="outputfilename", \
help="Output file sans variables, of form '*.nc'", metavar="FILE")
options, args = parser.parse_args()
if not options.inputfilename:
parser.error("Input filename or expression ('-f') is a required input... e.g., -f 'input*.nc'")
options, args = parser.parse_args()
if not options.inputfilename:
parser.error("Output filename or expression ('-o') is a required input... e.g., -o 'output*.nc'")
copy_netcdf_file_without_variables(options.inputfilename, options.outputfilename)