Mostly Linux & Python syntax notes and hyperlinks.

Tuesday, March 1, 2011

Python: appending column to end of tab-separated csv

Given this input file:
$ cat list.csv
a       b       c
d       e       f
g       h       i
Using this code:
import os,csv

def test_fcn() :
    try:
        tabReader = csv.reader( open("list.csv", "rb"), delimiter='\t', quoting=csv.QUOTE_NONE )
        fd = open("out.csv", "wb+")
        tabWriter = csv.writer(fd, delimiter='\t', quoting=csv.QUOTE_NONE)
        if tabReader != None :
            for record in tabReader:
                record.append("new_thing")
                tabWriter.writerow(record)
        fd.close()
        return

    except Exception,e :
        print "Exception : " + str(e)
        
def main():
    test_fcn()

if __name__ == '__main__':
    import sys
    main(*sys.argv[1:])
Here's the output:
$ cat out.csv
a       b       c       new_thing
d       e       f       new_thing
g       h       i       new_thing