合并多个不含头的CSV文件(使用Python) [英] Merging multiple CSV files without headers being repeated (using Python)

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

问题描述

我是Python的初学者。我有多个CSV文件(超过10),并且它们都有相同的列数。我想将它们合并成一个CSV文件,其中我不会重复头。

I am a beginner with Python. I have multiple CSV files (more than 10), and all of them have same number of columns. I would like to merge all of them into a single CSV file, where I will not have headers repeated.

所以本质上,我需要只有第一行与所有头,然后我需要所有CSV文件合并的所有行。

So essentially I need to have just the first row with all the headers and from then I need all the rows from all CSV files merged. How do I do this?

感谢!

b

推荐答案

虽然我认为最好的答案是来自@valentin的一个,你可以不使用 csv module at all:

While I think that the best answer is the one from @valentin, you can do this without using csv module at all:

import glob

interesting_files = glob.glob("*.csv") 

header_saved = False
with open('output.csv','wb') as fout:
    for filename in interesting_files:
        with open(filename) as fin:
            header = next(fin)
            if not header_saved:
                fout.write(header)
                header_saved = True
            for line in fin:
                fout.write(line)

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

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