Write Results to new column in excel spreadsheet

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kmartinenko
    New Member
    • Jan 2008
    • 12

    Write Results to new column in excel spreadsheet

    Hi all,

    I have come up with a solution on how to read a .csv file, perform a simple command on the values in one of the columns and then print the results onto the command prompt screen

    But what if I want the results to be written to a new column within the writeout (destination) file? I am sure this isn't an uncommon function of reading/writing .csv files in excel dialect?

    Here is my code:

    Code:
    import csv 
    sourcefile = open('H:/LoadData.csv', 'rb')
    outfile = open('H:/LoadData_out.csv', 'wb')
    source = csv.reader(sourcefile, dialect='excel') #tells the program what format sourcefile is in
    dest = csv.writer(outfile, dialect='excel') #tells the program what format the destination file is in
    
    for lst in source:  #define csv file as a matrix, Python starts at zero.  Columns are skipped, hence, LOAD is column 5, not column 3
        print lst[0], lst[1], lst[2], lst[3]  # TIME, DIR, LOCATION, LOAD
        x = float(lst[3])     #define LOAD as an integer
        try:
            if x >= 20:
                print 'load greater than 20'
                dest.writerow(lst)
            else:
                print 'load less than 20'
         
        except ValueError:   #error handling...if value is null or not in the correct format
            print 'value null', repr(lst)    #returns list as a parseable object
    What it prints out (in part):
    3:45:00 PM OUTBOUND COMMERCIAL & MYERS 22.80
    load greater than 20
    3:45:00 PM OUTBOUND COMMERCIAL & RURAL 22.90
    load greater than 20
    3:45:00 PM OUTBOUND COMMERCIAL & VISTA 19.50
    load less than 20
    3:45:00 PM OUTBOUND COMMERCIAL & MADRONA 18.80
    load less than 20
    3:45:00 PM OUTBOUND COMMERCIAL & BROWNING 18.00
    load less than 20
    3:45:00 PM OUTBOUND COMMERCIAL & WELCOME 20.00
    load greater than 20
    3:45:00 PM OUTBOUND COMMERCIAL & HILFIKER 19.00
    load less than 20
    3:45:00 PM OUTBOUND COMMERCIAL & KEGLERS 17.80
    load less than 20

    I want it to export these results to the LoadData_out.cs v file, with the 'load is greater/less than 20' statement in a new column.

    Thanks in advance!
Working...