glayne glayne - 2 months ago 6
Python Question

Add a new column to a csv file in python

I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column.

This is what I have so far:

with open(filename) as csvin:
readfile = csv.reader(csvin, delimiter=',')
with open(output, 'w') as csvout:
writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
for row in readfile:
result = [str(row[10]) + ' ' + str(row[11])]
writefile.writerow(result)


Any help would be appreciated.

Answer

No input to test, but try this. Your current approach doesn't include the existing data for each row that already exists in your input data. extend will take the list that represents each row and then add another item to that list... equivalent to adding a column.

with open(filename) as csvin:
    readfile = csv.reader(csvin, delimiter=',')
    with open(output, 'w') as csvout:
        writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
        for row in readfile:
            row.extend([str(row[10]) + ' ' + str(row[11])])
            writefile.writerow(row)