How to concatenate two columns and update the csv in python?
<p>In Excel, I would be able to use something like this:</p>

<pre><code>=CONCATENATE(A1," ",B1) 
</code></pre>

<p>(User flood fill's this down the spreadsheet, and then simply deletes A and B, lastly you move results to A)</p>

<p>End Result is expected to have A and B columns merged into one column (A) and separated by one space.</p>

<p>In Python here is what I have so far:</p>

<pre><code>import csv
with open("test.csv","rb") as source:
    rdr= csv.reader( source )
    with open("result","wb") as result:
        wtr= csv.writer( result )
        for r in rdr:
            print("Adding merged COL1/COL2 into one column for every row...")
            wtr.writerow(r+[r[0] + ' ' + r[1]])
            print("Deleting COL1/COL2 columns from every row...")
            del r[0]
            del r[0]
            wtr.writerow( r )
    result.close();
</code></pre>

<p>Although, the above code does properly merge two columns and append a column to the end of the file, it does not properly delete the first two rows once it is finished, I believe this is because wtr.writerow has already been called. Also, I am unsure how to move the column to the left (back to A), since it always appends to the end.</p>

<p>You're calling <code>writerow</code> twice in that loop. I don't think you want that - writing the merged columns and then the others separately? No.</p>

<p>You can simply join the merged columns to the <em>start</em> of the rows, and <em>slice off</em> the old rows:</p>

<pre><code>wtr.writerow([r[0] + ' ' + r[1]] + r[2:])
#            ^&lt;- merged rows are added to the start
#                                   ^&lt;- slice off old A1 and B1
</code></pre>

<p>You won't need the <code>del</code> statements any longer, and one call to <code>writerow</code> inserts your modified <em>row</em>:</p>

<pre><code>import csv 

with open("test.csv","rb") as source, open("result","wb") as result:
    rdr = csv.reader(source)
    wtr = csv.writer(result)
    for r in rdr:
        wtr.writerow([r[0] + ' ' + r[1]] + r[2:])
</code></pre>

<p>Also, note that you can put multiple expressions after a <code>with</code> statement, like I did above.</p>

<hr>

<p>Finally, you don't need to manually close the file - <code>result.close()</code>. The <code>with</code> context already <em>manages</em> that.</p>

python csv