How two merge several .csv files horizontally with python?

后端 未结 6 550
渐次进展
渐次进展 2021-01-14 16:11

I\'ve several .csv files (~10) and need to merge them together into a single file horizontally. Each file has the same number of rows (~300) and 4 header lines which are not

6条回答
  •  无人及你
    2021-01-14 16:42

    You dont need to use csv module for this. You can just use

    file1 = open(file1)
    

    After opening all your files you can do this

    from itertools import izip_longest
    
    foo=[]
    for new_line in izip_longest(file1,fil2,file3....,fillvalue=''):
        foo.append(new_line)
    

    This will give you this structure (which kon has already told you)..It will also work if you have different number of lines in each file

    [ ("line10", "line20", "line30", "line40"),
      ("line11", "line21", "line31", "line41"),
      ... 
    ]
    

    After this you can just write it to a new file taking 1 list at a time

    for listx in foo:
        new_file.write(','.join(j for j in listx))
    

    PS: more about izip_longest here

提交回复
热议问题