如何两个合并几个.csv文件水平与python? [英] How two merge several .csv files horizontally with python?

查看:599
本文介绍了如何两个合并几个.csv文件水平与python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个.csv文件(〜10),需要将它们一起水平合并成一个文件。每个文件具有相同的行数(〜300)和4个标题行,不一定相同,但不应合并(只从第一个.csv文件的标题行)。行中的标记是逗号分隔的,之间没有空格。



作为一个python noob我没有提出一个解决方案,虽然我确定有一个简单的解决这个问题。欢迎任何帮助。

解决方案

您可以使用 csv 模块。请参阅此模块的文档了解加载代码,但我不记得了真的很容易。例如:

  import csv 
reader = csv.reader(open(some.csv,rb ))
csvContent = list(reader)

  [(header1,header2,header3, header4),
(value01,value12,value13,value14),
(value11,value12,value13,value14),
...
]

您可以逐行合并两个此类列表

  result = [a + b for(a,b)in zip(csvList1,csvList2)] 

要保存此类结果,您可以使用:

  writer = csv.writer(open(some.csv,wb))
writer.writerows(result)
pre>

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 necessarily identical, but should not be merged (only take the header lines from the first .csv file). The tokens in the lines are comma separated with no spaces in between.

As a python noob I've not come up with a solution, though I'm sure there's a simple solution to this problem. Any help is welcome.

解决方案

You can load the CSV files using the csv module in Python. Please refer to the documentation of this module for the loading code, I cannot remember it but it is really easy. Something like:

import csv
reader = csv.reader(open("some.csv", "rb"))
csvContent = list(reader)

After that, when you have the CSV files loaded in such form (a list of tuples):

[ ("header1", "header2", "header3", "header4"),
  ("value01", "value12", "value13", "value14"),
  ("value11", "value12", "value13", "value14"),
  ... 
]

You can merge two such lists line-by-line:

result = [a+b for (a,b) in zip(csvList1, csvList2)]

To save such a result, you can use:

writer = csv.writer(open("some.csv", "wb"))
writer.writerows(result)

这篇关于如何两个合并几个.csv文件水平与python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆