Add a new column to a csv file in python
<p>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. </p>

<p>This is what I have so far:</p>

<pre><code>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)
</code></pre>

<p>Any help would be appreciated.</p>

<p>I assume that glayne wants to combine column 10 and 11 into one.
In my approach, I concentrate on how to transform a single row first:</p>

<pre><code>def transform_row(input_row):
    output_row = input_row[:]
    output_row[10:12] = [' '.join(output_row[10:12])]
    return output_row
</code></pre>

<p>Once tested to make sure that it works, I can move on to replace all rows:</p>

<pre><code>with open('data.csv') as inf, open('out.csv', 'wb') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    writer.writerows(transform_row(row) for row in reader)
</code></pre>

<p>Note that I use the <code>writerows()</code> method to write multiple rows in one statement.</p>

python python-2.7 csv