Merging multiple CSV files without headers being repeated (using Python)

前端 未结 5 724
长情又很酷
长情又很酷 2020-12-08 01:38

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,

5条回答
  •  [愿得一人]
    2020-12-08 01:54

    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)
    

提交回复
热议问题