diff options
-rwxr-xr-x | scripts/csv2sto.py | 85 |
1 files changed, 85 insertions, 0 deletions
diff --git a/scripts/csv2sto.py b/scripts/csv2sto.py new file mode 100755 index 0000000..8e5300b --- /dev/null +++ b/scripts/csv2sto.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python + +import os, sys +import getopt +import csv + +DEFAULT_NAME = 'control' + +def usage(): + print """usage: %s [OPTION...] CSV-FILE STO-FILE + + -f force overwrite of existing files + -n name of the sto file (default: %s) + -h show this help and exit""" % (DEFAULT_NAME, os.path.basename(sys.argv[0])) + +def main(): + try: + opts, args = getopt.getopt(sys.argv[1:], "fh") + except getopt.GetoptError, err: + print(str(err)) + usage() + sys.exit(-1) + + if len(args) < 2: + usage() + sys.exit(-1) + elif len(args) > 2: + print "Merging CSV files currently not supported, only %s considered" % args[1] + + overwrite = False + name = DEFAULT_NAME + for o, a in opts: + if o == '-f': + overwrite = True + elif o == '-n': + name = a + elif o == '-h': + usage() + sys.exit(0) + else: + assert False, "unhandled option" + + f_csv = args[0] + f_sto = args[-1] + if not os.path.exists(f_csv): + print "Error: CSV file %s does not exist" % f_csv + sys.exit(-1) + if not overwrite and os.path.exists(f_sto): + print "Error: STO file %s already exists" % f_sto + sys.exit(-1) + + # determine number of columns and rows + fd = open(f_csv, 'r') + nRows = nColumns = 0 + for line in fd: + if nRows == 0: + nCols = len(line.split(',')) + nRows += 1 + fd.close() + + fd_sto = open(f_sto, 'w') + fd_sto.write(name + "\n") + fd_sto.write("nRows=" + str(nRows) + "\n") + fd_sto.write("nColumns=" + str(nColumns) + "\n") + fd_sto.write("endheader\n") + + print "Writing sto file %s with name %s" % (f_sto, name) + + colname = os.path.splitext(f_csv)[0] + print "[+] Adding muscle %s..." % colname + fd_sto.write("time\t" + colname + "\n") + + fd_csv = open(f_csv, 'r') + cr = csv.reader(fd_csv, delimiter=',') + + for i, row in enumerate(cr): + if i == 0: + continue # skip header line + fd_sto.write("\t".join(row) + "\n") + + fd_csv.close() + fd_sto.close() + +if __name__ == '__main__': + main() |