source: trunk/UTIL/replace_variable.py @ 3555

Last change on this file since 3555 was 1817, checked in by emillour, 7 years ago

A simple python script to replace a variable in a netcdf file by one (of same name and shape) from another file.
EM

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