Appending two CSV files column-wise

前端 未结 2 774
日久生厌
日久生厌 2021-01-27 08:38

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

A\'s head looks like:

 headerName         


        
2条回答
  •  清歌不尽
    2021-01-27 09:15

    If you get two file handles for the same file - one in 'read' mode, one in 'update' mode (r+b), the same strategy should work.

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

    When possible I'd recommend against this kind of thing and just explicitly write to a third file.

提交回复
热议问题