1 | #!/usr/bin/env python |
---|
2 | # coding: utf-8 |
---|
3 | |
---|
4 | import argparse |
---|
5 | import netCDF4 |
---|
6 | |
---|
7 | ## parse script arguments |
---|
8 | parser=argparse.ArgumentParser(description="Load a variable from a first file to (over-)write it in a second file") |
---|
9 | ## add a mandatory argument |
---|
10 | parser.add_argument("file1",help="first input file name") |
---|
11 | ## add another mandatory argument |
---|
12 | parser.add_argument("file2",help="second input/output file name") |
---|
13 | ## add another mandatory argument |
---|
14 | parser.add_argument("variable",help="variable to read from first file and (over-)write to second file") |
---|
15 | |
---|
16 | # get arguments |
---|
17 | args=parser.parse_args() |
---|
18 | filename1=args.file1 |
---|
19 | filename2=args.file2 |
---|
20 | varname=args.variable |
---|
21 | |
---|
22 | print "Replacing variable ",varname," in ",filename2," by the one in ",filename1 |
---|
23 | |
---|
24 | # open files |
---|
25 | try: |
---|
26 | dset1=netCDF4.Dataset(filename1,"r") # read only |
---|
27 | except: |
---|
28 | print "Error: cannot find file ",filename1 |
---|
29 | exit() |
---|
30 | |
---|
31 | try: |
---|
32 | dset2=netCDF4.Dataset(filename2,"a") # read/write |
---|
33 | except: |
---|
34 | print "Error: cannot find file ",filename2 |
---|
35 | exit() |
---|
36 | |
---|
37 | # load data |
---|
38 | try: |
---|
39 | data1=dset1.variables[varname] |
---|
40 | except: |
---|
41 | print "Error, cannot find variable ",varname," in file ",filename1 |
---|
42 | exit() |
---|
43 | |
---|
44 | try: |
---|
45 | data2=dset2.variables[varname] |
---|
46 | except: |
---|
47 | print "Error, cannot find variable ",varname," in file ",filename2 |
---|
48 | exit() |
---|
49 | |
---|
50 | # copy data1 into data2 |
---|
51 | if data2.shape != data1.shape: |
---|
52 | print "Error: shape mismatch for variable ",varname," between the 2 files!" |
---|
53 | print " ",data1.shape," in ",filename1 |
---|
54 | print " ",data2.shape," in ",filename2 |
---|
55 | exit() |
---|
56 | nd2 = data2.ndim # number of dimensions of data2 |
---|
57 | if nd2 == 1: data2[:]=data1[:] |
---|
58 | elif nd2 == 2: data2[:,:]=data1[:,:] |
---|
59 | elif nd2 == 3: data2[:,:,:]=data1[:,:,:] |
---|
60 | elif nd2 == 4: data2[:,:,:,:]=data1[:,:,:,:] |
---|
61 | |
---|
62 | # close file to write data to file |
---|
63 | dset2.close() |
---|
64 | |
---|
65 | print "All's well that ends well." |
---|
66 | |
---|