#!/usr/bin/env python import os import sys from netCDF4 import Dataset def nc_subset(in_file, out_file): # Remove the output file, if it exists if os.path.exists(out_file): os.remove(out_file) # Open the input file: nc_in = Dataset(in_file, 'r') # Create the output file try: nc_out = Dataset(out_file, 'w', format="NETCDF4") except IOError as e: print("Could not create output file {}: {}".format(out_file, e.args[1]), file=sys.stderr) exit(2) # Copy the dimensions for name, dimension in nc_in.dimensions.items(): nc_out.createDimension(name, len(dimension) if not dimension.isunlimited() else None) # Copy the variables for name, variable in nc_in.variables.items(): if name in ['time', 'reference_time', 'x', 'y', 'RAINRATE']: nc_out.createVariable(name, variable.datatype, variable.dimensions) nc_out[name].setncatts(nc_in[name].__dict__) nc_out[name][:] = nc_in[name][:] elif name in ['crs']: nc_out.createVariable(name, 'S1') nc_out[name].setncatts(nc_in[name].__dict__) # Copy the global attributes for k, v in nc_in.__dict__.items(): nc_out.setncattr(k, v) nc_out.close() nc_in.close() if __name__ == '__main__': if len(sys.argv) != 3: print("usage: python thinnedPrecipMR.py input_file output_file", file=sys.stderr) sys.exit(1) if os.path.exists(sys.argv[1]): nc_subset(sys.argv[1], sys.argv[2]) else: print("Input file not found: {}".format(sys.argv[1]), file=sys.stderr) sys.exit(1)