How to use python to add a column to a csv file?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ronparker
    New Member
    • Aug 2010
    • 27

    #1

    How to use python to add a column to a csv file?

    Hello all!
    I have a csv file which is usually has between 100 and 200 columns. I have a new column of data that I want to add to the csv file. I know if you open the file as "A" it will append the file, but I only know how to use it to add new rows to the document. not new columns.
    Right now this code will write three columns of data:
    Code:
    myFile= open( "CC4.csv", "wb" )
    wtr= csv.writer( myFile )
    for blanka,s,q in zip(blanka,s,q):
    	wtr.writerow([blanka,s,q])
    myFile.close()
    Now assuming I have an array called "data" and I don't know how many columns are already written in the file, how can I add this new column to the file?

    Thank you,
    Ron Parker
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Read the existing CSV file. Create a new array of data and append the new columns to each row. Then write the new array to disc. An example:
    Code:
    import csv
    
    f = open('csv2.txt')
    data = [item for item in csv.reader(f)]
    f.close()
    
    new_column = ["Col 1", "Line 1", "Line 2"]
    
    new_data = []
    
    for i, item in enumerate(data):
        try:
            item.append(new_column[i])
        except IndexError, e:
            item.append("placeholder")
        new_data.append(item)
    
    f = open('csv2B.txt', 'w')
    csv.writer(f).writerows(new_data)
    f.close()

    Comment

    Working...