Skip to content Skip to sidebar Skip to footer

Combining CSV Files Column-wise

Suppose I have two CSV files called A and B in Python. A's head looks like: headerNameA1,headerNameA2 1.12412424,1 1,1 1,1 1,1 B's head looks like: headerNameB1,headerNameB2

Solution 1:

You can consume one line at a time from both files, concatenating them together and writing to your outfile. The csv module makes things a bit cleaner.

import csv
with open('A','rb') as f1, open('B','rb') as f2, open('out.csv','wb') as w:
    writer = csv.writer(w)
    r1,r2 = csv.reader(f1),csv.reader(f2)
    while True:
        try:
            writer.writerow(next(r1)+next(r2))
        except StopIteration:
            break

And as @RogerPate points out, you can make this slicker with itertools.izip (just zip if you're in python3)

from itertools import izip
import csv
with open('A','rb') as f1, open('B','rb') as f2, open('out.csv','wb') as w:
    writer = csv.writer(w)
    for r1,r2 in izip(csv.reader(f1),csv.reader(f2)):
        writer.writerow(r1+r2)

Post a Comment for "Combining CSV Files Column-wise"