Combining CSV files column-wise

后端 未结 1 445
余生分开走
余生分开走 2021-01-15 22:43

Suppose I have two CSV files called A and B in Python.

A\'s head looks like:

 header         


        
相关标签:
1条回答
  • 2021-01-15 23:24

    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)
    
    0 讨论(0)
提交回复
热议问题