tonemgub - 10 months ago 70
Python Question

# How to concatenate two columns and update the csv in python?

In Excel, I would be able to use something like this:

=CONCATENATE(A1," ",B1)


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

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

In Python here is what I have so far:

import csv
with open("test.csv","rb") as 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();


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.

So every row you're reading from (and writing to) csv is a list, right? So take another step or two and create the list you want, then write it.

e.g.

import csv
with open('test.csv') as f: