Python - File sorts

From PeformIQ Upgrade
Jump to navigation Jump to search

Example

#!/usr/bin/env python
#
#  $Id:$
#
#-------------------------------------------------------------------------------

"""
Sort CSV data to generate LoadRunner parameter files
"""

import os
import csv
import sys
import getopt
import random
import datetime

#-------------------------------------------------------------------------------

debug_flg          = False
max_flg            = False
random_flg         = False
verbose_flg        = False

__version__        = '1.0.0'

source_data        = 'Names.dat'
sorted_data        = 'Sorted.dat'

header             = None
no_columns         = None
rows               = []

#==== Misc Sort Functions ======================================================

def by_Col0_as_Int(item1, item2):
   return cmp(int(item1[0]), int(item2[0]))

#-------------------------------------------------------------------------------

def by_Col1_as_UCAlpha(item1, item2):
   return cmp(item1[1].upper(), item2[1].upper())

#----- Read in source CSV data to be transposed --------------------------------

def read_csv():
   global no_columns
   global header

   csv_in  = open(source_data, "rb")

   reader = csv.reader(csv_in)

   cnt = 0

   for row in reader:
      cnt += 1
      if cnt == 1:
         header = row
         continue
      l  = len(row)
      if no_columns:
        if l != no_columns:
           print "Exception at row %d  Found %d columns - should be %d\n%s" % (cnt, no_columns, l, row)
      else:
         no_columns = l

      rows.append(row)

   csv_in.close()  # Explicitly close the file *NOW*

   no_rows = len(rows)

   print "Read %d rows" % no_rows

   return no_rows

#----- Sort the data -------------------------------------------------

def sort():
   out = open(sorted_data,"w")

   #rows.sort(by_Col0_as_Int)
   rows.sort(by_Col1_as_UCAlpha)

   out.write('%s,%s\n' % (header[0], header[1]))

   for row in rows:
      out.write('%s,%s\n' % (row[0], row[1]))

   out.close()

#-------------------------------------------------------------------------------

USAGE = """\

  Usage:

     $ ./sort.py [-d] [-v] [-f <filename>]

"""

def usage():
   sys.stderr.write(USAGE)

#-------------------------------------------------------------------------------

def main(argv):
   global debug_flg
   global verbose_flg
   global file

   #----- Process command line arguments ----------------------------

   try:
      opts, args = getopt.getopt(argv, "df:hv",
                 ["debug", "file=", "help", "verbose"])
   except getopt.GetoptError:
      usage()
      sys.exit(2)
   else:
      for opt, arg in opts:
         if opt in ("-d", "--debug"):
            debug_flg = True
         elif opt in ("-f", "--file"):
            logfile = arg
         elif opt in ("-h", "--help"):
            usage()
            sys.exit(0)
         elif opt in ("-v", "--verbose"):
            verbose_flg = True

   read_csv()
   sort()

#-------------------------------------------------------------------------------

if __name__ == "__main__":
    main(sys.argv[1:])

#-------------------------------------------------------------------------------