【问题标题】:Merge multiple csv's using python使用python合并多个csv
【发布时间】:2013-07-25 04:56:21
【问题描述】:

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

CSV1

ABC,1

防御,2

GHI,3

CSV2

ABC,4

防御,5

GHI,6

等等最多 15 个 csv 文件。

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

ABC, 1, 4

防御、2、5

GHI, 3, 6

感谢任何有关如何执行此操作的指针。

【问题讨论】:

  • 到目前为止你有没有尝试过?甚至研究过?
  • 也许可以尝试使用 google.com 查询 python csv?

标签: python csv merge


【解决方案1】:
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()])

【讨论】:

    【解决方案2】:

    假设所有 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))
    

    【讨论】:

    • 使用with时不需要f.close()。我还建议查看DictReader
    • 谢谢,这是习惯的力量。
    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 2013-04-22
    相关资源
    最近更新 更多