Home > Software design >  Python CSV, Combining multiple columns into one column using CSV
Python CSV, Combining multiple columns into one column using CSV

Time:03-30

I've been trying to figure out a way to combine all the columns in a csv I have into one columns.

import csv
with open('test.csv') as f:
    reader = csv.reader(f)
    with open('output.csv', 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = [' '.join([row[0], row[1]])]   row[2:]
            writer.writerow(new_row)

This worked to combine the first two columns, but I've been having trouble trying to loop it and get the rest of the columns into just one.

CodePudding user response:

You should just pass row to .join because it's an array.

import csv
with open('test.csv') as f:
    reader = csv.reader(f)
    with open('output.csv', 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = [' '.join(row)] # <---- CHANGED HERE
            writer.writerow(new_row)
  • Related