#!/usr/bin/env python # Copyright 2010 Rod Person . All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY ROD PERSON ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import sys import os from optparse import OptionParser __doc__=""" Copyright 2010 Rod Person : swap_columns (c) 2010 This is a script to read in a delimited file and rearrange the columns. Command Line Switches: -f - filename -d - delimiter. If not present defualts to ',' -m - tuple of tuple of column swaps. Such as (1,3),(5,9) -o - output file name -h - display this screen EXAMPLE: python sc.py -f infile.txt -d , -m (1,3),(5,9) -o outfile.txt Open the file 'infile.txt' that is delimited by ',' swap column 1 with 3 and column 5 and 9 and write to outfile.txt """ def main(): parser = OptionParser() parser.add_option("-f","--file",dest="FILE_NAME",help="File to read") parser.add_option("-d","--delimiter",default=",",dest="DELIMITER") parser.add_option("-m","--columns",dest="SWAP",help="A tuple of tuples contain column pairs to swap. Such as ((1,3),(5,9))") parser.add_option("-o","--output-file",dest="OUTFILE") (options, args) = parser.parse_args() '''if len(args) != 1: parser.error("missing required arguments")''' if options.SWAP: SWAP = eval(options.SWAP) DELIMITER = options.DELIMITER FILE_NAME = options.FILE_NAME OUTFILE = options.OUTFILE tmp_file={} in_file = open(FILE_NAME) idx = 0 for line in in_file: line = line.strip('\n') values = line.split(DELIMITER) tmp_file[idx] = values idx += 1 for line in tmp_file: for set in SWAP: b = tmp_file[line][set[1]] tmp_file[line][set[1]] = tmp_file[line][set[0]] tmp_file[line][set[0]] = b out_file = open(OUTFILE,'w+') for k in tmp_file: nl = "" for v in tmp_file[k]: nl += '%s,' % v nl = nl.rstrip(',') out_file.write(nl + '\n') print 'DONE' if __name__ == "__main__": main()