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

前端 未结 5 739
长情又很酷
长情又很酷 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 02:11

    Your indentation is wrong, you need to put the loop inside the with block. You can also pass the file object to writer.writerows.

    import csv
    with open('output.csv','wb') as fout:
        wout = csv.writer(fout)
        interesting_files = glob.glob("*.csv")
        for filename in interesting_files:
            print 'Processing',filename
            with open(filename,'rb') as fin:
                    next(fin) # skip header
                    wout.writerows(fin)
    

提交回复
热议问题