aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rwxr-xr-xcsv_tool24
1 files changed, 19 insertions, 5 deletions
diff --git a/csv_tool b/csv_tool
index 674c51c..e747462 100755
--- a/csv_tool
+++ b/csv_tool
@@ -9,6 +9,7 @@ import defapp
9 9
10import csv 10import csv
11import operator 11import operator
12import os.path
12from collections import defaultdict as defdict 13from collections import defaultdict as defdict
13 14
14o = optparse.make_option 15o = optparse.make_option
@@ -22,6 +23,9 @@ opts = [
22 o('-c', '--column', action='store', dest='col', type='int', 23 o('-c', '--column', action='store', dest='col', type='int',
23 help='The column on which to operate.'), 24 help='The column on which to operate.'),
24 25
26 o(None, '--write-to-file', action='store_true', dest='write_to_file',
27 help='Write the output of operation xyz on file abc.csv to xyz_abc.csv.'),
28
25# o(None, '--true', action='store_true', dest='truth', 29# o(None, '--true', action='store_true', dest='truth',
26# help='A boolean flag value.'), 30# help='A boolean flag value.'),
27 31
@@ -30,8 +34,9 @@ opts = [
30 ] 34 ]
31 35
32defaults = { 36defaults = {
33 'col' : 0, 37 'col' : 1,
34 'col_xcgh' : [], 38 'col_xcgh' : [],
39 'write_to_file' : False,
35 } 40 }
36 41
37def make_vector_op(op): 42def make_vector_op(op):
@@ -109,9 +114,11 @@ def select_by_key(rows, col, cast=None):
109class CsvApp(defapp.App): 114class CsvApp(defapp.App):
110 def __init__(self): 115 def __init__(self):
111 defapp.App.__init__(self, opts, defaults) 116 defapp.App.__init__(self, opts, defaults)
117 # fixup human-friendly offsets
112 self.options.col -= 1 118 self.options.col -= 1
113 self.options.col_xchg = [(x - 1, y - 1) for (x, y) in 119 if self.options.col_xchg:
114 self.options.col_xchg] 120 self.options.col_xchg = [(x - 1, y - 1) for (x, y) in
121 self.options.col_xchg]
115 122
116 def transform(self, make_iterator, ordered=True): 123 def transform(self, make_iterator, ordered=True):
117 """Average all rows with the same key in a given column.""" 124 """Average all rows with the same key in a given column."""
@@ -129,7 +136,14 @@ class CsvApp(defapp.App):
129 else: 136 else:
130 rows = make_iterator(rows) 137 rows = make_iterator(rows)
131 # write out 138 # write out
132 csv.writer(self.outfile()).writerows(rows) 139 outfile = self.outfile()
140 if self.options.write_to_file:
141 (dir, file) = os.path.split(fn)
142 fn = os.path.join(dir, self.args[0] + '_' + file)
143 outfile = open(fn, 'w')
144 csv.writer(outfile).writerows(rows)
145 if self.options.write_to_file:
146 outfile.close()
133 except IOError, ex: 147 except IOError, ex:
134 self.err("%s:%s" % (fn, str(ex))) 148 self.err("%s:%s" % (fn, str(ex)))
135 except IndexError, ex: 149 except IndexError, ex: