forked from pfuhe1/cpdn_extract_scripts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompress_extracted_netcdf.py
53 lines (41 loc) · 1.43 KB
/
compress_extracted_netcdf.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
#!/usr/bin/env python2.7
#############################################################################
# Program : compress_extracted_netcdf.py
# Author : Sarah Sparrow
# Date : 19/02/2020
# Purpose : Apply lossless compression to already extracted netcdf files
# in the specified directory
#############################################################################
import os, sys, shutil
import argparse
import glob
import netCDF4 as nc4
def compress_netcdf(fname):
os.system('nccopy -d 2 -s '+fname+' '+fname+'_compressed')
shutil.move(fname+'_compressed',fname)
def check_compression(fname):
fn=fname.split('/')
varname=fn[-2]
ds=nc4.Dataset(fname)
var = ds.variables[varname]
try:
complevel=var.filters().get('complevel',False)
except:
complevel=None
print('Compression level '+str(complevel))
return complevel
def main():
#Read in the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("dir", help="The directory containing the netCDF files you want to compress")
args = parser.parse_args()
iter_files=glob.iglob(os.path.join(args.dir,"*.nc"))
for fname in iter_files:
print("Compressing file "+fname)
complevel=check_compression(fname)
if complevel==None:
compress_netcdf(fname)
print('Finished!')
#Washerboard function that allows main() to run on running this file
if __name__=="__main__":
main()