使用python合并多个csv

时间:2013-07-25 04:56:21

标签: python csv merge

我是python的新手,我已经达到了从大文本文件创建多个csv文件的地步。所以我的csv看起来如下。

CSV1

ABC,1

DEF,2

GHI,3

CSV2

ABC,4,

DEF,5

GHI,6

以及最多15个csv文件。

我想创建一个组合的csv文件,如下所示。

ABC,1,4,

DEF,2,5

GHI,3,6

有关如何执行此操作的任何指示表示赞赏。

2 个答案:

答案 0 :(得分:0)

假设所有CSV文件的长度相同且包含相同顺序的相同第一列,则此类内容可能对您有用:

list_of_files = ['csv1.csv', 'csv2.csv', 'csv3.csv']

# Use the first file as a template
with open(list_of_files[0], 'r') as f:
    output_text = [line.strip() for line in f]

# Append the values to the end of the lines
for fn in list_of_files[1:]:
    with open(fn, 'r') as f:
        for i, line in enumerate(f):
            key, value = line.strip().split(",")
            output_text[i] += "," + value

# Dump result to new csv
with open("result.csv", 'w') as f:
    f.write("\n".join(output_text))

答案 1 :(得分:0)

import csv
from collections import defaultdict

csvs = ["data1.csv", "data2.csv"]
for file in csvs:
    for line in csv.reader(open(file)):
        d.setdefault(line[0], []).append(line[1]) 

with open("result.csv", "w") as f:
    wrt = csv.writer(f)
    wrt.writerows([[k] + v for k, v in d.items()])