Skip to content

Instantly share code, notes, and snippets.

@shurane
Created July 12, 2011 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shurane/1078704 to your computer and use it in GitHub Desktop.
Save shurane/1078704 to your computer and use it in GitHub Desktop.
Question asked earlier today -- but this should be legible and understandable. Everything is outputted to "MQ_List-output.csv"
#!/usr/bin/env python
import csv
import sys
import os.path
#filename1 = csv with all the important rows (inputfile)
#filename2 = csv that sorts filename1 by groups (sortby)
#filename3 = alternate filename, by default it is filename1 appended with '-output.csv' (output_file)
if len(sys.argv) <= 2:
print "usage: %s inputfile sortbyfile [outputfile]" % sys.argv[0]
sys.exit(0)
filename1 = sys.argv[1]
filename2 = sys.argv[2]
try:
filename3 = sys.argv[3]
except IndexError:
basename, ext = os.path.splitext(filename1)
filename3 = "%s-output.csv" % basename
inputfile = open(filename1)
sortby = open(filename2)
outputfile = open(filename3, "w")
mq_list = [row for row in csv.reader(inputfile)]
themap = [row for row in csv.reader(sortby)]
output = csv.writer(outputfile)
map_lookup = {}
grouped_by = {}
for symbol,group in themap:
map_lookup[ symbol ] = group
grouped_by[ group ] = []
for row in mq_list:
try:
grouped_by[ map_lookup[ row[0] ] ] += [row]
except KeyError:
print "couldn't find group of %s" % row[0]
for k in sorted(grouped_by.keys()):
for row in grouped_by[k]:
output.writerow(row)
inputfile.close()
sortby.close()
outputfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment