python批量合并csv,使用python合并多个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

and so on for upto 15 csv files.

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值