使用python合并多个csv [英] Merge multiple csv's using python

查看:1322
本文介绍了使用python合并多个csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的python和我有一个点,我已经从大文本文件创建了多个csv文件。所以我的csv看起来像下面。

I am new to python and I have got to a point where I have created multiple csv file from large text files. So my csv's look like below.

CSV1

ABC,1

DEF ,2

GHI,3

CSV2

ABC,4

DEF,5

GHI 6

等等,最多15个csv文件。

and so on for upto 15 csv files.

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

I would like to create a combined csv file which looks something like below.

ABC,1,4

DEF,2,5

GHI,3,6

任何指点如何做到这一点是赞赏。

Any pointers on how to do this is appreciated.

推荐答案

假设所有CSV文件的长度相同,并且包含相同顺序的第一列,为您工作:

Assuming all the CSV files are of the same length and contain the same first column in the same order, something like this might work for you:

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))

这篇关于使用python合并多个csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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